创建“n”循环中的矩阵

发布于 2024-11-09 12:38:14 字数 442 浏览 0 评论 0原文

可能的重复:
如何将数字连接到变量名称MATLAB?

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

像这样:

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”的矩阵。

预先感谢您,祝您有美好的一天!

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

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

Like this:

for (i=1:n)

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

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

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!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

作业与我同在 2024-11-16 12:38:14

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

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 个不同的矩阵,那么您将需要一个 元胞数组。您的代码将类似于:

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 子块等)。

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

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文