Search code examples
matlabmatlab-guide

Multiple conditions with 'if' statement


How to Set multiple conditions with 'if' statement

I want my 'if' statement to execute at particular values of a counter variable 'i' where 'i' ranges from 1:100 and 'if' statement should execute at i=10,20,30,40,..100. How can I set the condition with 'if' statement?

for i=1:100
if i=10||20||30||40||50||60||70||80||90||100
fprintf('this is multiple of 10') % 1st section
else
fprintf('this is not multiple of 10') % 2nd section
end

I expect that '1st section should only execute when 'i' equals multiple of 10 but in actual, '1st section' executes always.


Solution

  • For your specific case (i.e. is a number a multiple of 10), the answer from machnic using the mod (or rem) function is the best approach:

    if mod(i, 10) == 0 ...
    % Or
    if rem(i, 10) == 0 ...
    

    For a more general case (i.e. is a number in a given set), you have a few options. You could use the any function on the result of a vectorized equality comparison:

    if any(i == 10:10:100) ...
    

    Or you could use the ismember function:

    if ismember(i, 10:10:100) ...