matlab - 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.
解决方案
正如评论中所建议的,对于这种简单的条件,您可以使用mod
函数:
for i = 1:100
if mod(i, 10) == 0
fprintf('%i - this is multiple of 10\n', i) % 1st section
else
fprintf('%i - this is not multiple of 10\n', i) % 2nd section
end
end