필터 지우기
필터 지우기

if function in cell arrays

조회 수: 2 (최근 30일)
gsourop
gsourop 2016년 11월 19일
댓글: the cyclist 2016년 11월 19일
Hi everyone,
I try to use to use the if function in cell arrays. If I have A that is 2x100 cells and each cell contains a 6x1 vector. I need to set the following constraint:
for k=1:2
for t=1:100
if A{k,t}(:,1)<-1;
A{k,t}(:,1)=-1;
elseif A{k,t}(:,1)>2;
a{k,t}(:,1)=2;
end;
end;
end;
This code does not deliver an error. However, it doesn't do what I aim at. It should go on each cell and check the each value of the vectors have a value over or lower than the if statements.
Thanks in advance

답변 (1개)

the cyclist
the cyclist 2016년 11월 19일
편집: the cyclist 2016년 11월 19일
There are a couple issues with your code. The main issue is that the line
A{k,t}(:,1)<-1
will have a vector output, and therefore the if statement is not doing what you expect. (It would have to be true for every value in the vector, to trigger the if.)
A more straightforward way to do this is as follows:
for k=1:2
for t=1:100
A{k,t} = max(A{k,t},-1);
A{k,t} = min(A{k,t}, 2);
end
end
which compares each element of the vector to the threshold value, and replaces it if necessary.
This same operation can be done very compactly, eliminating the for loops completely, with the cellfun function instead:
A = cellfun(@(x)max(x,-1),A,'UniformOutput',false);
A = cellfun(@(x)min(x, 2),A,'UniformOutput',false);
You can even collapse this into a one-liner:
A = cellfun(@(x)min(2,max(x,-1)),A,'UniformOutput',false);
but what you are doing starts to get a little "obfuscated".
(The for loop seems to be the faster method, though, in the limited testing I did.)
  댓글 수: 2
gsourop
gsourop 2016년 11월 19일
Thanks a lot! I've started working on cell arrays to create a more compact and fast way for the first steps of my code, but then it has started getting more comfusing than I expected.
the cyclist
the cyclist 2016년 11월 19일
The best form of thanks is upvoting and/or accepting helpful answers, which rewards the contributors, and guides future users.

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

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by