Generate n-dimensional array: problem with 1D

3 次查看(过去 30 天)
Hi all,
Imagine I'd like to generate random dimensional zeros matrix, I can do:
K>> zeros(2, 2)
ans =
0 0
0 0
K>> zeros(2, 2, 2)
ans(:,:,1) =
0 0
0 0
ans(:,:,2) =
0 0
0 0
and so on. However, for 1D case, I'll have to use:
K>> zeros(2, 1)
ans =
0
0
I cannot use zeros(2) directly, meaning I have to deal with 1D case separately. Any idea how to make it smarter?

采纳的回答

Star Strider
Star Strider 2017-11-8
That is as ‘smart’ as it gets, since it cannot read your mind. If you already have a vector and you want a zeros vector to match it, you can use the size of the original vector (or any dimension array) to create it:
x = 1:2;
v = zeros(size(x));
  2 个评论
Xiaohan Du
Xiaohan Du 2017-11-8
For example, I know the dimension of the zeros matrix I'd create, say for 2D, it's
zeros(2, 3)
for 3D, it's
zeros(2, 3, 4)
for 4D, it's
zeros(2, 3, 4, 5)
but for 1D, if I want a 2-by-1 matrix, I cannot write
zeros(2)
because this gives me a 2-by-2 matrix. I'll have to write
zeros(2, 1)
I understand that zeros(2, 1) also exists in 2D, but it does not completely follow the rules for nD.
Star Strider
Star Strider 2017-11-8
That is the default behaviour of the zeros function. You can always write your own single-argument function to create a column vector of zero elements:
myzeros = @(n) zeros(n,1);

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by