Generating a matrix with specific sums
8 次查看(过去 30 天)
显示 更早的评论
Dear all,
I am trying to generate a matrix based on specific sums. Let's say I generate the following matrix
X = randi([0 400], 6, 6);
Which gives me the matrix X. Now I want to sum x11 and x21, x12 and x22, x21 and x22, and so on. This should give me a 3x6 matrix. Does anyone have any clue how to do this effectively?
Best
4 个评论
采纳的回答
Image Analyst
2022-1-2
The pattern is confusing, like Torsten says. Is this what you mean?
X = randi([0 400], 6, 6)
X2 = [...
sum(X(1:2, :), 1); ...
sum(X(3:4, :), 1); ...
sum(X(5:6, :), 1); ]
4 个评论
Image Analyst
2022-1-3
If you have some other even number of rows, you can use a for loop:
X = randi([0 400], 8, 3)
[rows, columns] = size(X);
X2 = zeros(rows/2, columns);
newRow = 1;
for row = 1 : 2 : rows
X2(newRow, :) = sum(X(row : row+1, :), 1);
newRow = newRow + 1; % Increment pointer
end
X2 % Show in command window.
更多回答(1 个)
Paul
2022-1-2
Another solution:
X = randi([0 400], 6, 6)
kron(eye(3),[1 1])*X
7 个评论
Paul
2022-1-3
If you want to know more about the kron() function, start with its doc page.
Mathematically, all that's happening is matrix multiplication. Is that the part of the solution you're asking about?
FWIW, this solution probably isn't the most efficient what with all the multiplications by zero and summing up terms that are zero. Probably better to just pre-allocate the answer and use a simple loop over the sum() function (basically a minor extension of Image Analyst's solution) to fill in the rows of the anwer.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!