If loop using cell arrays
Show older comments
Hi,
I have 2 matrices:
A with 24 arrays of each different length (i.e. A{1} 2362x1, A{2} 2341x1) defining salaries
B with 24 arrays of each different length (i.e. A{1} 2362x1, A{2} 2341x1) contains either a 0 or a 1
And last I have 2 boundary values C= 2600 and D= 1700.
I want to check the following:
if B(each value) == 0 && A(each value) > C
A(this value)= C
elseif B(each value) == 1 && A(each value) > D
A(this value)= D
end
Can anyone help me out?
1 Comment
Walter Roberson
on 14 Sep 2015
There is no such thing as an "if loop". There are "for loop" and there are "while loop" and there are "if statement". A loop would have to execute its body multiple times, but "if" executes the body only 1 time or 0 times.
Accepted Answer
More Answers (1)
Titus Edelhofer
on 14 Sep 2015
Hi,
I'm not 100% sure I understand what you want to do, but I guess it should be like this
for i=1:length(A)
if all(B{i}(:)==0 & A{i}(:)>C)
A{i}(:) = C;
elseif all(B{i}(:)==1 & A{i}(:)>D)
A{i}(:) = D;
end
end
Titus
4 Comments
Titus Edelhofer
on 14 Sep 2015
length(A) is the length of the cell array. The code is (just as Guillaume's code) totally independent of the sizes of each A{i}, B{i} (of course as long as they match) :).
Titus
Both codes have the following preconditions:
assert(isequal(numel(A), numel(B)));
assert(all(cellfun(@(a,b) isequal(size(a), size(b)), A, B)));
Titus Edelhofer
on 14 Sep 2015
I wish I could vote for a comment! Nice assert calls.
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!