How to sum specific elements of a matrix

27 ビュー (過去 30 日間)
Alex
Alex 2021 年 6 月 9 日
編集済み: David Hill 2021 年 6 月 11 日
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 件のコメント
Stephen23
Stephen23 2021 年 6 月 9 日
"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"
How does 29 + 348 = 189 ?
Giving us an example that matches your description make it easier for us to help you.
Alex
Alex 2021 年 6 月 9 日
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.

サインインしてコメントする。

回答 (2 件)

Jan
Jan 2021 年 6 月 9 日
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 2021 年 6 月 9 日
編集済み: David Hill 2021 年 6 月 11 日
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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by