Form a large matrix from n numbers of small matrices

自作多情 提交于 2019-12-02 22:45:02

问题


I am a new to MATLAB. I have generated n smaller matrices of numbers, say 3 x 1 by using a FOR loop. All the matrices are having random values like so:

m1 = [3;2;1];   
m2 = [5;1;6];
m3 = [0.2;0.8;7]
m4 = [8;3;0] 
m5 = [3;7;6]
m6 = [8;2;1.3].

Now I want to concatenate all the values into a larger matrix M such that M can be represented like this:

M = [m1 m2 m3; m4 m5 m6]

So that the output of M shall be:

M = [3 5 0.2;
     2 1 0.8;
     1 6 7;
     8 3 8; 
     3 7 2;
     0 6 1.3];

How do I initialize that by using a FOR loop or anything else so that every time the increase of the counter value i.e i, this will result in an insertion of a new matrix (m1,m2 & so on) inside the bigger matrix i.e M?

Note that M is a very large matrix (maybe around 40 x 40) and so I am having a lot of smaller matrices.


回答1:


Do your really need the individual variables? Probably such a solution is simpler, using only one mmatrix:

M=zeros(40,40)
for idx=1:size(M,1)
   M(idx,:)=your_code_here()
end

Whenever you would have used M1 before, now use M(1,:) to get the first row of M




回答2:


This seems as highly inefficient way to put matrices together, but every MatLab newbie should pass through this stage in his evolution. If you use for loop, you should create your matrices in such a way that they can be indexed using your loop variable, otherwise there is no point to use the loop. Try cell arrays, for example:

m{1}=[3;2;1];
m{2}=[5;1;6];
m{3}=[.2;.8;7];
m{4}=[8;3;0];
m{5}=[3;7;6];
m{6}=[8;2;1.3];

Now you can merge them in a for loop:

M = [];
NBlocks = length(m) / 3;
for b=1:NBlocks
    M = [M; [m{(b-1)*3+1} m{(b-1)*3+2} m{(b-1)*3+3}] ];
end

NOTE This code is highly inefficient, especially for big matrices, and provided only for educational purposes. Consider redesigning your task to use matrix preallocation for your M matrix.



来源:https://stackoverflow.com/questions/25458285/form-a-large-matrix-from-n-numbers-of-small-matrices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!