[英]Array inside array in MATLAB
If n=4
for example, How to create an array like this in MATLAB? 例如,如果n=4
,如何在MATLAB中创建这样的数组?
[[0] [0 0] [0 0 0] [0 0 0 0]]
Is there a way to create an array inside a for
loop, for example ? 例如,有没有办法在for
循环中创建一个数组? This is what I want to achieve (I know it's wrong code): 这是我想要实现的(我知道这是错误的代码):
for i=1:n
table(i)=zeros(i);
end
You need a cell array to hold your numeric vectors. 您需要一个单元格数组来保存数字向量。 Cell arrays are used in Matlab when the contents of each cell are of different size or type. 当每个细胞的内容具有不同的大小或类型时,在Matlab中使用细胞阵列。
Additional comments: 附加评论:
i
to k
, to avoid shadowing the imaginary unit. 我将你的变量i
重命名为k
,以避免影响虚构单位。 table
to t
, to avoid shadowing the table
function. 我也将你的变量table
重命名为t
,以避免影响table
函数。 zeros(k)
gives a k
x k
matrix of zeros. zeros(k)
给出k
× k
的零矩阵。 To obtain a row vector of zeros use zeros(1,k)
. 要获得零的行向量,请使用zeros(1,k)
。 Taking the above into account, the code is: 考虑到上述因素,代码是:
n = 4;
t = cell(1,n); %// preallocate: 1xn cell array of empty cells
for k = 1:n
t{k} = zeros(1,k);
end
This gives: 这给出了:
>> celldisp(t)
t{1} =
0
t{2} =
0 0
t{3} =
0 0 0
t{4} =
0 0 0 0
Equivalently, you could replace the for
loop by the more compact arrayfun
: 等效地,你可以用更紧凑的arrayfun
替换for
循环:
result = arrayfun(@(k) zeros(1,k), 1:n, 'uniformoutput', false);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.