Storing Matrices of different sizes

조회 수: 6 (최근 30일)
Andrew
Andrew 2013년 6월 19일
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

채택된 답변

Iain
Iain 2013년 6월 19일
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
Andrew
Andrew 2013년 6월 19일
편집: Andrew 2013년 6월 19일
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!!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by