Form a large matrix from n numbers of small matrices

前端 未结 2 436
再見小時候
再見小時候 2021-01-28 18:04

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 v

2条回答
  •  臣服心动
    2021-01-28 18:21

    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.

提交回复
热议问题