assigning matrices to a cell

Right I apologise in advance because I have the feeling that what I've done may be some awful mistake that makes people with more matlab experience shudder but the concept of cells are kind of new to me.
Essentially I have a loop that creates a matrix Y each time I run it and I want to store this for use later in the code so that I can compare its entries with another array that I've created (successfully I might add!). At first I thought about using 3D arrays but then I realised that this meant all the cells needed to be the same size. This is a stripped down version of the relevant section of my code...
for k=1:K2
Y=zeros(N,D);
for n=1:N
if (r(n,k)==1)
Y(n,:)=X(n,:);
end
end
for n=N:-1:1
if ((sum(Y(n,:)))==0)
Y(n,:)=[];
end
end
Y=sortrows(Y);
Bla_2{:,k}=Y;
end
Can anyone please explain what I've done wrong and please use simple language. Thanks.

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2011년 6월 9일

0 개 추천

help:
doc all
doc function_handle
doc arrayfun
cod:
l1 = all(X,2);
X1 = X(l1,:);
r1 = r(l1,:)==1;
Bla_2 = arrayfun(@(ii)X1(r1(:,ii),:),1:K2,'un',0);

댓글 수: 4

Natalie
Natalie 2011년 6월 9일
So you determine the entries of X that are non-zero and reassign these values only to X and find the corresponding entries of r that are equal to one? Then what's the function ii and what does 'un' do?
Natalie
Natalie 2011년 6월 9일
Sorry just realised ii's the arglist! I still don't completely understand how this works though sorry. So you use arrayfun to apply X1 to 1:K2 but this isn't an array and X1 isn't a function or is this where the handle comes in?!
Andrei Bobrov
Andrei Bobrov 2011년 6월 9일
ii - the column index varies from 1 to K2.
arrayfun uses an anonymous function @ (ii) X1 (r1 (:, ii),:), for each ii, and places the result in a single cell cellarray (sorry for my english).
In this, the better to read the help on the functions -
"function_handle", "arrayfun".
Natalie
Natalie 2011년 6월 9일
Thanks Andrei. I understand now.

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

추가 답변 (2개)

Matt Fig
Matt Fig 2011년 6월 8일

0 개 추천

Use:
Bla_2{k} = Y;
But before the outer loop starts, pre-allocate the cell array:
Bla_2 = cell(K2,1);
Natalie
Natalie 2011년 6월 9일

0 개 추천

Thank you both. I'll have another try.

카테고리

도움말 센터File 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