[英]Matlab: Can I create a matrix with unknown number of dimensions?
Normally a matrix has 2 dimensions, but there doesn't seem to be a limit on the number of dimensions a matrix may have in MATLAB. 通常,一个矩阵有2维,但是在MATLAB中,矩阵的维数似乎没有限制。
To create a 4-dimensional matrix, for example, I can do this: 例如,要创建一个4维矩阵,我可以这样做:
>> x = zeros(2,2,2,2)
x(:,:,1,1) =
0 0
0 0
x(:,:,2,1) =
0 0
0 0
x(:,:,1,2) =
0 0
0 0
x(:,:,2,2) =
0 0
0 0
Is there a way to create a matrix of which the number of dimensions is only known at runtime? 有没有一种方法可以创建仅在运行时才知道维数的矩阵?
You could call zeros
like this: 您可以这样称呼
zeros
:
x = zeros([2 2 2 2])
Hence, you can customize the input array as you want. 因此,您可以根据需要自定义输入数组。
For example: to create a 2x2x2x2x2 matrix (where D = 5, the number of dimensions): 例如:创建一个2x2x2x2x2矩阵(其中D = 5,维数):
D = 5;
x = zeros(zeros(1, D) + 2)
Rafael's answer hits the nail on the head. 拉斐尔的答案打在了头上。 But there's also a general way to do this sort of thing even when the function doesn't have an overload for something like a vector input as in the case of
zeros
. 但是,即使函数没有像矢量输入那样的重载(如
zeros
的情况),也存在一种通用的方法来执行此类操作。 You can use a cell
array like so: 您可以像这样使用
cell
数组:
>> dims = {2,2,2,2};
>> zeros(dims{:})
ans(:,:,1,1) =
0 0
0 0
ans(:,:,2,1) =
0 0
0 0
ans(:,:,1,2) =
0 0
0 0
ans(:,:,2,2) =
0 0
0 0
I've found this approach to be very useful for other functions. 我发现这种方法对于其他功能非常有用。
Edit: 编辑:
This approach is more robust. 这种方法更健壮。 Here's another example:
这是另一个例子:
imginfo = { rand(40), [0 1], 'Colormap', colormap(jet) };
figure, imshow(a{:});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.