How would I keep adding matrices to an array using a for loop?

조회 수: 2 (최근 30일)
tash7827
tash7827 2015년 8월 3일
답변: the cyclist 2015년 8월 3일
I have managed to concatenate two matrices, but I would like to have ten total - what is wrong with my code?
A=zeros(60,96);
for exp = 1:10;
n=1;
while n<61
pop=randperm(96,60);
m = pop(n);
A(n,m)=1;
start=A;
array=cat(3,start,A);
n=n+1;
end
end
  댓글 수: 1
Sean de Wolski
Sean de Wolski 2015년 8월 3일
Perhaps this will help clarify for us: What is your end goal, i.e. what do you want the end array to look like (forget the steps for getting there right now)?

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

채택된 답변

the cyclist
the cyclist 2015년 8월 3일
It is not perfectly clear to me what you are trying to do, but I think the core of your problem is that in the line
array=cat(3,start,A);
You simply append start and A, over and over again. This does not "grow" the array. It just keeps making a (60,96,2) array.
It seems that what you actually want to do is to append to array, and then keep appending to array. So, maybe you want this line to be something like
array=cat(3,start,array);
Does that seem right?
Now, that being said, growing an array like this is a bad idea, from a memory usage point of view. Better practice (with potentially huge execution time benefit) would be to preallocate array
array = zeros(60,96,10)
and then fill in each "slice" as you go.
But it is OK start by fixing your own code, before you worry about optimizing.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by