understanding an if statement

1 view (last 30 days)
kalana agampodi
kalana agampodi on 28 Oct 2021
Edited: DGM on 28 Oct 2021
What does this mean ?
Can you please explain with an example ?
if not(max(c))c
Thanks

Accepted Answer

DGM
DGM on 28 Oct 2021
Edited: DGM on 28 Oct 2021
This isn't very clear usage and looks like invalid syntax at first glance. It would help to know what the surrounding code looks like and what c is (its size and type).
What looks like invalid syntax (an implicit multiplication with the trailing instance of c) is actually parsed like this:
c = [0 1 2 3]; % let's assume c is a numeric or logical vector
if not(max(c)) % true if largest value of c is <= 0
c % this is treated as a separate expression on another line
disp('tested true')
else
disp('tested false')
end
tested false
The condition will only test true if all elements of c are less than or equal to zero. You could do the same thing like so:
if all(c<=0) % true if c contains no positive nonzero values
% ...
end
Given the way this is written, it's not clear that this is the actual intent.
If the intent is for the test to be true only when all elements of c are equal to zero, you could do that instead:
if all(c==0) % true if c contains no nonzero elements
% ...
end
or
if nnz(c) == 0 % true if c contains no nonzero elements
% ...
end
or
if ~any(c) % true if c contains no nonzero elements
% ...
end

More Answers (0)

Community Treasure Hunt

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

Start Hunting!