To change 12x12 matrix to 6X12

1 次查看(过去 30 天)
How can i add a loop to add the 1st two rows of a matrix and then 3rd and 4th row of a matrix and so on till the addition of 11th and 12th row so as to get a 6x12 matrix instead of 12x12 matrix.
for example:
r= 1 2 3 4
5 6 7 8
9 0 1 2
3 4 5 6]
that is 4x4 matrix.
answer= 6 8 10 12
12 4 6 8
converted to 2x4 matrix.
so similar manner how to convert 12x12 matrix to 6x12 matrix using any loop or normal command.
  1 个评论
madhan ravi
madhan ravi 2019-2-8
When you ask a question provide an example , don't edit the question after someone answers.

请先登录,再进行评论。

采纳的回答

madhan ravi
madhan ravi 2019-2-8
Answer = reshape(r(1:2:end)+r(2:2:end),[],size(r,2))

更多回答(1 个)

Guillaume
Guillaume 2019-2-8
No need for a loop:
m = randi([0 100], 12) %demo matrix
newm = permute(sum(reshape(m.', size(m, 2), 2, []), 2), [3 1 2])
Basically,
  • transpose the matrix (since matlab is organised by columns, not by rows, so a MxN matrix is now a NxM matrix
  • reshape so that the pairs of rows to sum are now in columns of 2, so an original MxN matrix is now a Nx2x(M/2) matrix
  • sum along the columns, so the orignal MxN matrix is now a Nx1x(M/2) matrix
  • and permute back to the original format: Nx1x(M/2) -> (M/2)xN

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by