How to multiply a 4x4 matrix with a 1x3 matrix in C? - c

If you already have a set 4x4 matrix.
Ex.
Matrix A = [1 2 3 4;
5 6 7 8;`
9 10 11 12;
13 14 15 16]
Matrix B = [1, 2, 3]
How would you convert Matrix A into C coding? Also what would there positions be in code? For position I mean: if I'm trying to multiply the first row into matrix B, can I do this?
A[1][0]*B[0]+A[1][1]*B[1]+A[1][2]*B[2]
Outline code:
main(){
int matrixA[4][4] = [{"1","2","3","4"};
{"5","6","7","8"};
{"9","10","11","12"};
{"13","14","15","16"}];
printf(matrix A);
return 0;
}

First of all you cannot multiply a 1×3 matrix with 4×4 matrix.
You should have matrices like m×n and n×p to get them multiplied (the result will be an m×p matrix).
Also for having a 4×4 matrix in C you should implement it like this:
int main()
{
int mat[4][4];
for(int i=0;i<=3;i++)
{
for(int j=0;j<=3;j++)
{
scanf("%d", &mat[i][j]);
}
}
return 0;
}

As far i can understand, you want to make a program to execute mathematical fractions related to matrices. Example in linear algebra. Matrix sizes are not checked, but you get the idea. In division you have to make the calculation of Array2^-1 to find it. Hope i helped. After you find it, multiply the result ,to Array1. In division however, things are more complicated. You need to approach your coding in different ways, depending to the array(matrix) dimensions you have. Exceptions must be included and need to read a bit of theory on how to divide those matrices. See https://en.wikipedia.org/wiki/Division_(mathematics) for more details.
#include <stdio.h>
#include <math.h>
int main(){
//counters
int i=0,j=0,k=0,sum=0;
//first array
int Array1[4][4] ={
{87,96,70,22},
{18,65,77,78},
{76,72,84,65},
{87,93,73,77}};
//second array
int Array2[4][4]={
{14,45,66,88},
{45,32,97,44},
{34,64,23,66},
{39,98,55,32}};
//result array.
int ResultArray[4][4];
// Add
for (i = 0; i < 4; ++i) {
for (j = 0; j < 4; ++j) {
ResultArray[i][j]= Array1[i][j]+Array2[i][j];
}
}
//result
printf("\tAdd Array1 and Array2\n");
for (i = 0; i < 4; ++i) {
for (j = 0; j < 4; ++j) {
printf(" %10d \t",ResultArray[i][j]);
}
printf("\n");
}
//subtract
for (i = 0; i < 4; ++i) {
for (j = 0; j < 4; ++j) {
ResultArray[i][j]= Array1[i][j]-Array2[i][j];
}
}
//result
printf("\tSubtract Array1 and Array2\n");
for (i = 0; i < 4; ++i) {
for (j = 0; j < 4; ++j) {
printf(" %10d \t",ResultArray[i][j]);
}
printf("\n");
}
//multiply
for (i = 0; i < 4; ++i) {
for (j = 0; j < 4; ++j) {
for (k = 0; k < 4; ++k) {
sum=sum+Array1[i][k]*Array2[k][j];
}
ResultArray[i][j]=sum;
sum=0;
}
}
//result
printf("\tMultiplication Array1 and Array2\n");
for (i = 0; i < 4; ++i) {
for (j = 0; j < 4; ++j) {
printf(" %10d \t",ResultArray[i][j]);
}
printf("\n");
}
return 0;
}

you can write like this:
int matrixA[4][4] = {
{ 1, 2, 3, 4},//matrixA[0][0] is 1
{ 5, 6, 7, 8},//matrixA[1][1] is 6
{ 9, 10, 11, 12},
{13, 14, 15, 16}
};
int matrixB[] = { 1, 2, 3};
for(int r = 0; r < 4; ++r){
for(int c = 0; c < 4; ++c){
printf("%3d", matrixA[r][c]);
}
printf("\n");
}

Let me help you a bit, but you in return help me understand the question. :)
Representation
Ok Matrices are represented using 2-d array.
Like
int a[][]= { {1,2,3,4}, {5,6,7,8},{9,10,11,12},{13,14,15,16}};
Matrix is ready. :)
If you want to create it on the fly..malloc() will be your friend.
Here I meant to say that you have to dynamically allocate the array.
For example:
int **a;
a= malloc(sizeof(int*)*m);
for(int i=0;i<m;i++)
a[i]=malloc(sizeof(int)*n);
Forming mxn matrix where m and n are got as input maybe.
How to multiply 2 matrices [ ofcourse compatible]?
Here in your case A[4x4] B[1x4] so p=4,m=1,q=4.
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++) {
for (k = 0; k < p; k++) {
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}

Related

Changing the position of a 2D array in a matrix in C language

here is the question :
have a two 2D array
int matrix1[4][5]={ {8,5,2,4,3}, {9,6,4,0,4}, {0,1,2,3,4}, {9,9,9,9,9}};
Without changing the elements in the row in the matrix1 The sum of the rows will be ordered from smallest to largest. finally I want to transfer it to matrix 2 . cant use copy or functions just the basic programming skills like ( for,array,if, )
matrix2 should look like this:
int matrix2[4][5]={{0,1,2,3,4}, {9,6,4,0,4}, {8,5,2,4,3}, {9,9,9,9,9}};
here is my code
int i, j, temp, plus = 0;
int matris1[4][5] = {
{8, 5, 2, 4, 3},
{9, 6, 4, 0, 4},
{0, 1, 2, 3, 4},
{9, 9, 9, 9, 9}};
int matris2[4][5];
int topla[4];
/*here I found sum of the rows*/
for (i = 0; i < 4; i++)
{
for (j = 0; j < 5; j++)
{
plus = plus + matris1[i][j];
}
topla[i] = plus;
plus = 0;
}
/*here I did the smallest to largest and copy to the array topla */
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
if (topla[i] < topla[j])
{
temp = topla[i];
topla[i] = topla[j];
topla[j] = temp;
}
}
}
/* cant transfer to the matrix2 HELP PLEASE :'( */
int k;
for (i = 0; i < 4; i++)
{
for (j = 0; j < 5; j++)
{
plus = plus + matris1[i][j];
}
for (k = 0; k < 4; k++)
{
if (plus == topla[k])
{
matris2[k] = matris1[i];
}
}
plus = 0;
}
for (i = 0; i < 4; i++)
{
for (j = 0; j < 5; j++)
{
printf("%d - ", matris2[i][j]);
}
printf("\n");
}
You can create a struct remembering the sum and a pointer to the corresponding data that gave that sum:
typedef struct
{
int* data;
int sum;
} sum_t;
Then it goes like this:
int matrix1[4][5] = { {8,5,2,4,3}, {9,6,4,0,4}, {0,1,2,3,4}, {9,9,9,9,9} };
sum_t sum[4] = {0}; // set everything to zero
for(size_t i=0; i<4; i++)
{
sum[i].data = matrix1[i]; // remember which sum this is for later
for(size_t j=0; j<5; j++) // calculate sum
{
sum[i].sum += matrix1[i][j];
}
}
Next you'd call a sort function like qsort. But since you can't do that because of artificial requirements, you could just spew out some inefficient, manual version:
// school book example of a bad sort function:
void shitty_bubble_sort (size_t n, sum_t arr[n])
{
for(size_t i=0; i<n-1; i++)
{
for(size_t j=0; j<n-i-1; j++)
{
if(arr[j].sum > arr[j+1].sum)
{
sum_t tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
}
}
}
}
Usage: shitty_bubble_sort(4,sum);
That bubble sort function is the same thing you did when sorting topla, the only real difference is the loop indices and that I'm moving structs instead of integers.
Then create the next matrix based on the sorted sums:
int matrix2[4][5];
for(size_t i=0; i<4; i++)
{
shitty_memcpy(&matrix2[i], sum[i].data, sizeof(matrix2[i]));
printf("{ ");
for(size_t j=0; j<5; j++)
{
printf("%d ", matrix2[i][j]);
}
printf("}\n");
}
Where shitty_memcpy is just like ordinary memcpy but slower, for the benefit of your artificial requirments:
//school book example of a naive memcpy
void shitty_memcpy (void* dst, const void* src, size_t n)
{
unsigned char* d = dst;
const unsigned char* s = src;
for(size_t i=0; i<n; i++)
{
d[i] = s[i];
}
}
Complete example here: https://godbolt.org/z/ra8jenWWM. If you aren't allowed to use functions at all, then inlining those two functions manually is left as an exercise.

Multiplying two matrixes in C

I'm trying to multiply two matrixes in C but the result gives me:
\23 23\
\23 23\
instead of
\23 20\
\55 48\
1x1 of the matrix keeps repeating and it seems like the matResult[i][j]=sum isn't taking in the sum. The number of rows and columns are defined and there are no scans. I also used a function to calculate the multiplication of the matrix so that I could later use it in the main.
#include <stdio.h>
#define M 2 // m is the number of rows
#define N 2 // n is the number of columns
int i;
int j;
int k;
int sum;
/*
Function to calculate the multiplication of 2 matrixes
*/
int multiMat(int mat1[M][N], int mat2[M][N], int matResult[M][N]) {
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
for (int k = 0; k < N; k++) {
sum = sum + (mat1[i][k] * mat2[k][j]);
}
matResult[i][j] = sum;
sum = 0;
}
}
return matResult[i][j];
}
int main(void) {
int mat1[M][N] = {{1, 2}, {3, 4}};
int mat2[M][N] = {{9, 8}, {7, 6}};
int matResult[M][N];
printf("\n\n RESULT ");
printf("\n ===============\n");
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
printf(" %d\t", multiMat(mat1, mat2, matResult));
}
printf("\n");
}
return 0;
}
Here's my version of your code cleaned up. I've removed M as your matrices are square and your code won't easily adapt to multiplying two non-square matrices (though, as I noted in a comment, you can multiply an M×N matrix by an N×P matrix, and the result is an M×P matrix).
#include <stdio.h>
#define N 2 // n is the size of the square matrices
static void multiMat(int mat1[N][N], int mat2[N][N], int matResult[N][N])
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
int sum = 0;
for (int k = 0; k < N; k++)
{
sum = sum + (mat1[i][k] * mat2[k][j]);
}
matResult[i][j] = sum;
}
}
}
static void printMat(const char *tag, int mat[N][N])
{
printf("%s (%dx%d):\n", tag, N, N);
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
printf(" %3d", mat[i][j]);
}
printf("\n");
}
}
int main(void)
{
int mat1[N][N] = {{1, 2}, {3, 4}};
int mat2[N][N] = {{9, 8}, {7, 6}};
int mat3[N][N];
multiMat(mat1, mat2, mat3);
printMat("Mat1", mat1);
printMat("Mat2", mat2);
printMat("Mat3", mat3);
return 0;
}
When run, it produces the output:
Mat1 (2x2):
1 2
3 4
Mat2 (2x2):
9 8
7 6
Mat3 (2x2):
23 20
55 48
The result (renamed Mat3 in this code) is what you wanted. It's often a good idea to print the inputs as well as the output — it ensures that the computer is thinking about things the same way you are. It also encourages writing functions like printMat(). It is possible to provide the dimensions of the matrices to the functions using VLA (variable-length array) notation. For example, a more general matrix multiply function might be:
void MatrixMuliply(size_t M, size_t N, size_t P, int mat1[M][N], int mat2[N][P], int mat3[M][P])
{
for (int i = 0; i < M; i++)
{
for (int j = 0; j < P; j++)
{
int sum = 0;
for (int k = 0; k < N; k++)
sum += mat1[i][k] * mat2[k][j];
mat3[i][j] = sum;
}
}
}

How to create a program that reads nine integers into a 3x3 array

#include <stdio.h>
int main()
{
int test[2][3][2];
printf("Enter nine values: \n");
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 1; ++k)
{
scanf("%d", &test[i][j][k]);
}
}
}
// Printing values with proper index.
printf("\nDisplaying values:\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
}
}
}
return 0;
}
Perhaps I am just doing this wrong but I am having trouble in understanding how to get my program to read only 9 integers an output a 3x3 array from the user. What am I doing wrong?
You want to use a 2D array (a matrix in other words), of dimension 3x3, so eventually what you need is something like this:
int arr[3][3];
which creates a 2D array with 3 rows and 3 columns. In your attempt, you used a 3 dimensional array, which is not what you want.
I think you will understand the rest (which you already know from what I see from your good attempt) from my example:
#include <stdio.h>
#define N 3
#define M 3
int main(void)
{
int arr[N][M] = {0};
for(int i = 0; i < N; i++)
for(int j = 0; j < M; j++)
scanf("%d", &arr[i][j]);
for(int i = 0; i < N; i++)
{
for(int j = 0; j < M; j++)
printf("%d ", arr[i][j]);
printf("\n");
}
return 0;
}
See it also live.
You're not following the dimensions of your array at all. You have a 3-dimensional array here, dimensions 2 x 3 x 2. Assuming it gets filled with 0's, to help visualize:
[
[
[0, 0],
[0, 0],
[0, 0]
],
[
[0, 0],
[0, 0],
[0, 0]
]
]
Keep in mind an array is indexed 0 to n-1, where n is the size of the array.
Your first for-loop iterates to 2, which is equal to the size of your outermost array. That will result in a segmentation fault.
You should use a 2-dimensional array and #define your dimensions.

The reverse of all numbers on the 5th column on matrix [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have a C problem where I need to reverse all the numbers on the 5th column of a 2x5 matrix.
So if I have
1 2 3 4 89
3 8 6 8 91
This will become
1 2 3 4 98
3 8 6 8 19
The code I've written so far is:
#include <stdio.h>
void inverse() {
int reversedNumber = 0, remainder, mat[10][10], i, j;
for (i = 0; i < 2; i++)
for (j = 0; j < 5; j++) {
while (mat[i][j] != 0) {
remainder = mat[i][j] % 10;
reversedNumber = reversedNumber * 10 + remainder;
mat[i][j] /= 10;
}
}
printf("Reversed Number = %d", reversedNumber);
}
void main()
{
int mat[10][10], i, j;
printf("Enter your matrix\n");
for (i = 0; i < 2; i++)
for (j = 0; j < 5; j++) {
scanf("%d", &mat[i][j]);
}
printf("\nHere is your matrix:\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 5; j++) {
printf("%d ", mat[i][j]);
}
printf("\n");
}
inverse(mat[1][5]);
}
After running this I get a ridiculously large number! What should I modify?
There are number of things that can be improved in the code.
First of all you have to set reversedNumber zero inside the innermost loop, this is the reason you get large numbers.
You pass an argument to the function, but the definition is incorrect for the same.
Also, you have stated that you only need to reverse the 5th column, better make call to a function that reverses a single number.
#include<stdio.h>
int inverse(int num) {
int reversednum = 0;
while(num){
reversednum = reversednum*10 + num%10;
num /= 10;
}
return reversednum;
}
void main(){
int mat[10][10],i,j;
printf("Enter your matrix\n");
for(i=0;i<2;i++)
for(j=0;j<5;j++){
scanf("%d",&mat[i][j]);
}
printf("\nHere is your matrix:\n");
for(i=0;i<2;i++){
for(j=0;j<5;j++){
printf("%d ",mat[i][j]);
if(j == 4) mat[i][j] = inverse(mat[i][j]);
}
printf("\n");
}
}
mistakes in your program:
-your function doesnt expect anything i.e empty parameter but you are sending matrix as parameter.
do not unnecessarily use matrix of size [10][10] when your matrix of 2*5
send 'mat' as parameter(i.e address of your matrix) to function inverse
#include <stdio.h>
int main() {
//code
int mat[10][10], i, j;
printf("Enter your matrix\n");
for (i = 0; i < 2; i++)
for (j = 0; j < 5; j++) {
scanf("%d", &mat[i][j]);
}
printf("\nHere is your matrix:\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 5; j++) {
if(j==4) //only for 5th column
{
// int temp=mat[i][j]; // can use temporary variable instead of changing actual value matrix (better option)
int remainder, reverse =0;
while(mat[i][j]>0)
{
remainder=mat[i][j]%10;
reverse=reverse*10 + remainder;
mat[i][j]=mat[i][j]/10;
}
mat[i][j]=reverse;
}
printf("%d ", mat[i][j]);
}
printf("\n");
}
return 0;
}
Edited: modified code from the question
#include <stdio.h>
void inverse(int mat1[2][5]) {
int i, j;
for (i = 0; i < 2; i++){
int j=4;
int reversedNumber = 0, remainder=0;
while (mat1[i][j] > 0) {
remainder = mat1[i][j] % 10;
reversedNumber = reversedNumber * 10 + remainder;
mat1[i][j] /= 10;
}
printf("Reversed Number = %d\n",reversedNumber);
}
}
void main()
{
int mat[2][5], i, j;
printf("Enter your matrix\n");
for (i = 0; i < 2; i++)
for (j = 0; j < 5; j++) {
scanf("%d", &mat[i][j]);
}
printf("\nHere is your matrix:\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 5; j++) {
printf("%d ", mat[i][j]);
}
printf("\n");
}
inverse(mat);
}
hope this helps.
You have to pass the matrix to the inverse function so that the matrix (mat) can be modified. If you declare a separate mat array inside inverse then that's a different scope. You also have to figure out how many digits there are in the number. You can use <math.h> functions, or the example below uses basic calculations.
void inverse(int mat[2][5])
{
for(int i = 0; i < 2; i++)
for(int j = 0; j < 5; j++)
{
int n = mat[i][j];
int digits = 0;
while(n > 0)
{
digits++;
n /= 10;
}
n = mat[i][j];
int rev = 0;
while(digits > 0)
{
int x = n % 10;
for(int c = 0; c < digits - 1; c++)
x *= 10;
rev += x;
n /= 10;
digits--;
}
mat[i][j] = rev;
}
}
int main(void)
{
int mat[2][5] = {
1, 2, 3, 4, 89,
3, 8, 6, 8, 91 };
inverse(mat);
for(int i = 0; i < 2; i++)
{
for(int j = 0; j < 5; j++)
printf("%d ", mat[i][j]);
printf("\n");
}
return 0;
}

A matrix pointer into sub-matrices in C

I have this matrix in C.
[1,2,3,4]
[5,6,7,8]
[9,10,11,12]
[13,14,15,16]
n x n, squared matrix.
I need to split this into four matrices:
[1,2] [3,4] [9,10] [11,12]
[5,6] [7,8] [13,14] [15,16]
This will be represented inside an array like this:
array[16] = [1,2,5,6,3,4,7,8,9,10,13,14,11,12,15,16]
So far, I've done this:
int i,j;
int k = 0;
for(i = 0; i < 2; i++ )
{
for(j = 0; j < 2; j++)
{
array[k] = matrix[i][j];
k++;
}
}
for(i = 0; i < 2; i++ )
{
for(j = 2; j < 4; j++)
{
array[k] = matrix[i][j];
k++;
}
}
for(i = 2; i < 4; i++ )
{
for(j = 0; j < 2; j++)
{
array[k] = matrix[i][j];
k++;
}
}
for(i=2;i<4;i++)
{
for(j=2;j<4;j++)
{
array[k] = matrix[i][j];
k++;
}
}
As you can see, I've done 4 double for this, but, is there a dynamic way to do this? If I got a bigger matrix, like 8 x 8, how to do this? The split if bigger is the same as the example.
You should see the pattern of the routines you are duplicating.
Basically you do the same thing, except that the start and end of i and j are different. So create a sub routine and pass them as parameter.
For example:
void get_sub_matrix(int input[][N], int start_row, int end_row, int start_col, int end_col, int[] result, int* result_offset)
{
int offset = *result_offset;
for (int i = start_row; i < end_row; i++)
{
for (int j = start_col; j < end_col; j++)
{
result[offset++] = input[i][j];
}
}
*result_offset = offset;
}
Notice how the result-offset is increased inside the routine as more elements are added to the result array.
Now you can do:
int matrix[N][N];
int array[N*N];
int k = 0;
get_sub_matrix(matrix, 0, 2, 0, 2, array, &k);
get_sub_matrix(matrix, 0, 2, 2, 4, array, &k);
get_sub_matrix(matrix, 2, 4, 0, 2, array, &k);
get_sub_matrix(matrix, 2, 4, 2, 4, array, &k);
P.S: Haven't compiled it.

Resources