Clear Filters
Clear Filters

Subscripted assignment dimension mismatch ?

1 view (last 30 days)
MatlabFan
MatlabFan on 21 May 2013
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.

Answers (1)

Walter Roberson
Walter Roberson on 21 May 2013
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 Comments
MatlabFan
MatlabFan on 21 May 2013
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 on 21 May 2013
Edited: Walter Roberson on 21 May 2013
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

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!