From f94ec127f945bc3edc4aae2b67e5fb4e53c7ecf0 Mon Sep 17 00:00:00 2001 From: Your Name Date: Thu, 7 May 2026 19:24:29 +0200 Subject: [PATCH] add function --- matrix.c | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/matrix.c b/matrix.c index 4047e00..34ac577 100644 --- a/matrix.c +++ b/matrix.c @@ -50,7 +50,36 @@ return matrix.buffer [index]; // return the value at that index } Matrix add(const Matrix matrix1, const Matrix matrix2) -{ +{ if (matrix1.rows != matrix2.rows){ // check row compatibility + Matrix empty = {.rows =0, .cols=0, .buffer = NULL}; + return empty; +} + if (matrix1.cols!= matrix2.cols && matrix2.cols !=1 && matrix1.cols != 1){ // check column compatibility (allow broadcasting ) + Matrix empty = {.rows =0, .cols=0, .buffer =NULL}; + return empty; + } + unsigned int resultRows = matrix1.rows; //determine result dimensions + unsigned int resultCols = (matrix1.cols > matrix2.cols) ? matrix1.cols: matrix2.cols; + //Allocate memory for the result buffer + MatrixType *resultBuffer = malloc(resultRows * resultCols * sizeof(MatrixType)); + if (resultBuffer == NULL){ + Matrix empty = {.rows =0, .cols=0, .buffer=NULL}; + return empty; + } + // add elements element-wise with broadcasting + for (unsigned int row =0; row < resultRows; ++row){ + for (unsigned int col =0; col < resultCols; ++col){ + MatrixType val1 = getMatrixAt(matrix1, row, col); + //Handle broadcasting: if matrix2 has 1 column, use column 0 + unsigned int col2 = (matrix2.cols==1) ? 0 : col; + MatrixType val2 = getMatrixAt(matrix2, row, col2); + + unsigned int resultIndex = row * resultCols + col; + resultBuffer[resultIndex] = val1 +val2; + } + } + Matrix result = {.rows = resultRows, .cols = resultCols, .buffer= resultBuffer}; + return result; //create and return result }