Form a large matrix from n numbers of small matrices

爷,独闯天下 提交于 2019-12-02 12:01:17

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

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.

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