if function in cell arrays
1 view (last 30 days)
Show older comments
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
0 Comments
Answers (1)
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
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.
See Also
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!