Subscripted assignment dimension mismatch ?

1 次查看(过去 30 天)
Hi,
I would like to fill the columns of an array of unknown number of rows with elements from a known vector; such as:
for i=1:100
vector= {bunch of calculations to find vector}
array(:,i)= vector
end
where vector is a N x 1 vector, and we obviously don't know the maximum number of rows of array. What is a computationally efficient way of doing this?
Thanks.

回答(1 个)

Walter Roberson
Walter Roberson 2013-5-21
for i = 100: -1: 1
vector= {bunch of calculations to find vector}
array(:,i)= vector
end
Provided, of course, that the vector is the same length for all entries.
Alternately,
i = 1;
vector= {bunch of calculations to find vector}
array = zeros(length(vector), 100);
array(:,i) = vector
for i = 2 : 100
vector= {bunch of calculations to find vector}
array(:,i)= vector
end
  2 个评论
MatlabFan
MatlabFan 2013-5-21
Thanks Walter. In my case, vector is not the same length for all entries. I can find, or estimate the the maximum possible length of vector. So, in this case, using what you helped me with I would write:
i = 1;
vector= {bunch of calculations to find vector}
array = zeros(Maximum_length_vector, 100);
array(:,i) = vector
for i = 2 : 100
vector= {bunch of calculations to find vector}
array(:,i)= vector
end
Is that the most efficient way to do it, since vector is not the same length for all entries ?
Walter Roberson
Walter Roberson 2013-5-21
编辑:Walter Roberson 2013-5-21
If the vector length is not the same for all entries then you have a difficulty: what to do with the unoccupied locations if you are using a numeric array?
Urrr... where you wrote {bunch of calculations to find vector} was that intended to indicate creating a cell array?
Anyhow...
array = cell(100,1);
for i=1:100
vector= ... %bunch of calculations to find vector in numeric form
array{i} = vector;
end
This creates a cell array in which each entry is the proper length
or
array = NaN(Maximum_length_vector, 100);
for i=1:100
vector= ... %bunch of calculations to find vector in numeric form
array(1:length(vector),i) = vector;
end
This would leave NaN in the unused positions of a numeric array

请先登录,再进行评论。

类别

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