由 n 个小矩阵组成一个大矩阵 [英] Form a large matrix from n numbers of small matrices

查看:41
本文介绍了由 n 个小矩阵组成一个大矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 MATLAB 的新手.我使用 FOR 循环生成了 n 个较小的数字矩阵,比如 3 x 1.所有矩阵都具有如下随机值:

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].

现在我想把所有的值连接成一个更大的矩阵 M 使得 M 可以这样表示:

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]

这样 M 的输出应该是:

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];

我如何通过使用 FOR 循环或其他任何东西来初始化它,以便每次增加计数器值,即 i,这将导致插入一个新的矩阵(m1,m2 & 等等)在更大的矩阵内,即 M?

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?

请注意,M 是一个非常大的矩阵(可能约为 40 x 40),因此我有很多较小的矩阵.

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

推荐答案

这似乎是将矩阵组合在一起的效率极低的方法,但每个 MatLab 新手都应该在他的进化过程中经历这个阶段.如果您使用 for 循环,您应该以可以使用循环变量索引它们的方式创建矩阵,否则没有必要使用循环.试试元胞数组,例如:

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];

现在您可以将它们合并到 for 循环中:

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

注意 此代码效率极低,尤其是对于大矩阵,并且仅用于教育目的.考虑重新设计您的任务,为您的 M 矩阵使用矩阵预分配.

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.

这篇关于由 n 个小矩阵组成一个大矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆