Build matrix of different size column vectors generated inside a for loop

16 views (last 30 days)
Hi,
Inside a for loop, I am generating column vectors of different lengths that are being plotted against time for a number of datasets.
How do I take these different sized column vectors and store them in a matrix/ table/ array, such that the number of rows is equal to the longest column vector, and the number of columns is equal to the number of iterations in the for loop?
Where I have got up to:
for u = 1:length(listings)
ForceNext(u) = ForceTrunc(u);
ForceAll = zeros(75, 1);
ForceAll{:,u} = [ForceAll, ForceNext(u)]
end
I have also attached the full script, with lines 127 - 156 relating to the question. I will later take mean values of each row of the matrix I wish to create, and plotting the subsequent vector against a time series.
Thanks for any and all help
  3 Comments
Paul Broadley
Paul Broadley on 27 Jan 2021
Hi Bob,
For the current datasets, the longest will be 75 rows in length. However I was hoping to apply this for future generated data that will likely produce much more than 75 - and with many datasets, making it difficult to manually look at each and every length.
Thanks, I will attempt this for now
Bob Thompson
Bob Thompson on 27 Jan 2021
Is the size captured in one of your other dataset variables? If the size is captured somewhere else you can use that value to more organically specify the size of the array.

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 27 Jan 2021
Edited: Stephen23 on 27 Jan 2021
Inside the loop store the vectors in a preallocated cell array. Then after the loop use PADCAT (download required):
To get you started (pseudocode):
N = number of iterations
C = cell(1,N);
for k = 1:N
... your code
C{k} = output vector
end
M = padcat(C{:});
  1 Comment
Paul Broadley
Paul Broadley on 1 Feb 2021
This is great, thanks Stephen.
The final solution was as you've described, in combination with having built an array and attempted to append to it in the same nested for loop.
Thanks again :)

Sign in to comment.

More Answers (0)

Categories

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

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!