循环创建"n"个矩阵 [英] Create 'n' matrices in a loop

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

问题描述

可能重复:
如何在MATLAB吗?

Possible Duplicate:
How to concatenate a number to a variable name in MATLAB?

大家好,作为标题,我想了解是否有人知道如何在Matlab中循环创建'n'个矩阵.

Hi everyone, as the title, i'd like to learn if anyone knows how, in Matlab, create 'n' matrices in a loop.

赞:

for (i=1:n)

p_i = P(i, :);
q_i = Q(i, :);

A_i = [p_i, p_i', q_i];
end

Matlab当然会在矩阵A_i上重写n次,但是我希望有n个'i'索引矩阵.

Matlab, of course, rewrites n times on the matrix A_i, but i would like to have n matrices of 'i' index.

提前谢谢您,祝你有美好的一天!

Thank you in advance, have a good day!!

推荐答案

您可以将所有内容连接到3D数组中:

You could concatenate everything into a 3D array:

A_i = zeros(D1,D2,n);  % D1 and D2 are the dimensions of the 2D arrays
for i = 1:n
    p_i = P(i,:);
    q_i = Q(i,:);
    A_i(:,:,i) = [p_i, p_i', q_i];
end

如果您确实想要n个不同的矩阵,则需要一个 单元格数组 .您的代码将变为:

If you genuinely want n distinct matrices, then you will need a cell array. Your code would become something like:

A_i = cell(1,n);
for i = 1:n
    p_i = P(i,:);
    q_i = Q(i,:);
    A_i{i} = [p_i, p_i', q_i];
end

请注意,您应该仔细考虑哪种最适合您的需求.单元阵列的唯一真正优势在于,它允许每个元素成为不同的数据类型或不同大小的阵列.与2D阵列的单元阵列相比,3D阵列具有几个优点(您可以对其进行求和,重塑形状,从中切出3D子块等).

Note that you should carefully consider which would suit your needs the best. The only real advantage of a cell array is that it allows each element to be a different data-type, or a different-sized array. A 3D array has several advantages over a cell array of 2D arrays (you can sum over it, reshape it, slice 3D sub-chunks out of it, etc. etc.).

这篇关于循环创建"n"个矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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