MATLAB Answers

How to sum specific elements of a matrix

5 views (last 30 days)
Alex
Alex on 9 Jun 2021
Edited: David Hill on 11 Jun 2021
Hello, everyone. Let's say I have a 6x6 matrix of random numbers like the one below (in green). I want to create two new matrices, one 3x6 (in blue) and the second 9x3 (in orange). (i) The first one (so the one in blue) must contain in the first row the sum per column of the row vectors 1 and 4 of the main matrix, in the second row the sum of the row vectors 2 and 5, and finally in the third and last row the sum of the row vectors 3 and 6. (ii) As for the second one (the one in orange), it must contain in the first column the sum per row of vectors in columns 1 and 4 of the main matrix, in the second row the sum of vectors in columns 2 and 5, and in the third row the sum of vectors in columns 3 and 6, including the cells of the first matrix in blue created previously. (iii) The two new matrices created must then be attached to the main matrix to create a new matrix of size 9x9.
Hoping to have described the problem well - I also attach an explanatory image to follow - how can I get the result as efficiently as possible.
Thank you very much to anyone who helps me,
Alex
  5 Comments
Alex
Alex on 9 Jun 2021
Sorry, my mistake, these are averages, not sums. I wrote sums because I was searching the forum for something similar, as the (sum) operation is more commonly used.
The problem is really simple actually as a setup, just not being good with matlab I can't figure out how to set up the matrices. In Stephen's example 189 is the average between 29 and 348.

Sign in to comment.

Answers (2)

Jan
Jan on 9 Jun 2021
The most efficient solution is to ask in the forum, because this is faster than solving this problem by your own ;-)
X = randi([0, 400], 6, 6); % At least this should be solvable by beginners
Y = [X; X(1:3, :) + X(4:6, :)];
Z = [Y, Y(:, 1:3) + Y(:, 4:6)];

David Hill
David Hill on 9 Jun 2021
Edited: David Hill on 11 Jun 2021
m=randi(100,6);%your assumed matrix
m=[m;mean(m([1 4],:));mean(m([2 5],:));mean(m([3 6],:))];
b=[mean(m(:,[1 4]),2),mean(m(:,[2 5]),2),mean(m(:,[3 6]),2)];
m=[m,b];%new matrix

Products


Release

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by