if function in cell arrays

1 view (last 30 days)
gsourop
gsourop on 19 Nov 2016
Commented: the cyclist on 19 Nov 2016
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

Answers (1)

the cyclist
the cyclist on 19 Nov 2016
Edited: the cyclist on 19 Nov 2016
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 Comments
gsourop
gsourop on 19 Nov 2016
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 on 19 Nov 2016
The best form of thanks is upvoting and/or accepting helpful answers, which rewards the contributors, and guides future users.

Sign in to comment.

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!