Storing Matrices of different sizes

25 views (last 30 days)
Andrew
Andrew on 19 Jun 2013
Good morning everyone,
I am working on a project where I sequentially run the same process with two different inputs through the use of for loops. Out of this process I get a vector and a matrix that I would like to store. I am trying to do this with mxnxp arrays but run into the problem that the matrices are different sizes for each iteration. Specifically the matrix seems to be longer for later iterations than it is initially. Here's an example of the code I am trying to run:
tstepvec=60*10:60*10:60*30; %inputting the various time step values for iteration
varvec=1:10; %inputting the various variance values for iteration
Y=NaN(length(0:10:60*30),42,length(tstepvec)*length(sigmapvec)); %preallocating Y
T=NaN(length(0:10:60*30),1,length(tstepvec)*length(sigmapvec)); %preallocating T
zzz=1; %initializing variable
for tbs=tstepvec
for sigmapix=sigmapvec
[Y(:,:,zzz),T(:,:,zzz)]=process(tbs,sigmapix); %running the process
zzz=zzz+1; %updating variable
end
end
So, again, my problem is that I need some way to store Y and T sequentially even if they are different lengths due to the step size. The biggest problem I believe is that the length grows larger as the iterations progress, otherwise Matlab would just tack 0's on the end to fill in any elements that were missing. One solution I can possibly think of but don't know how to implement would be to change the indices from colons to some other term that tells matlab to just fill in the spaces that are available instead of removing any that are extra.
Anyway, any help would be greatly appreciated!
Thanks,
Andrew

Accepted Answer

Iain
Iain on 19 Jun 2013
Your best option is to use a cell array:
[Y{zzz}(:,:) T{zzz}(:,:)] = process(tbs,sigmapix);
Alternatively:
[Ytemp Ttemp] = process(tbs,sigmapix);
Y(1:size(Ytemp,1),1:size(Ytemp,2),zzz) = Ytemp; ... etc
  1 Comment
Andrew
Andrew on 19 Jun 2013
Edited: Andrew on 19 Jun 2013
Thanks, that looks like what I need but I admittedly have never used cell arrays before. What is the syntax to call the matrix later if I need values from it to plot. For instance, I need to plot T(:,1,1) and Y(:,7,1) later on, would I just use T{1}(:,1) and Y{1}(:,7)?
EDIT: I figured this one out on my own, but how would preallocating work? Its not crucial but the process takes a good amount of time to run by itself so I am trying to be as efficient as possible with my code. Thanks again!!

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!