|||
x=5;
% if-statement
Syntax: if x>0
end
% if-else-statement
Syntax: if x==5
fprintf ('x equals 5 n') % if x equals 5 then do this. n - new line
else
fprintf ('x is not equal to 5 n') % if x does not equal 5, then do this.
end
Output: x equals 5
% if-elseif-statement
Syntax: if x<=6 && x>=0 % && means "and"!
fprintf ('x is less than or equal to 6 and is greater than or equal to 0 n')
elseif x ==7
fprintf ('x equals 7 n') % if x is equal to 7, then do this.
end
% if-elseif-else-statement
Syntax: if x<=6 && x>=0 % && means "and"!
fprintf ('x is less than or equal to 6 and is greater than or equal to 0 n')
elseif x ==7
fprintf ('x equals 7 n') % if x is equal to 7, then do this.
else
fprintf ('x is something else') % if x is not less than or equal to 6, not greater than or equal to 0 and not equal to 7, then do this.
end
Output: x is less than or equal to 6 and is greater than or equal to 0
% nested if-statement
see e.g.3
Example 1: mark grading
mark=input('enter in a mark out of 100: ');
if mark<=100 && mark>=0
if mark>=85 % 85+
fprintf('the mark of %.0f is a high distinction n',mark);
elseif mark>=75 % 75+ (but less than 85)
fprintf('the mark of %.0f is a distinction n',mark);
elseif mark>=65 % 65+ (but less than 75)
fprintf('the mark of %.0f is a credit n',mark);
elseif mark>=50 % 50+ (but less than 65)
fprintf('the mark of %.0f is a pass n',mark);
else % less than 50
fprintf('the mark of %.0f is a fail n',mark);
end
else % the input is invalid: mark>100 or mark<0
fprintf('Not a valid input, mark must be between 0-100 n');
end
Example 2: day of week
function day_of_week(n)
if n==1
fprintf('Sunday, ');
day_type=2;
elseif n==2
fprintf('Monday, ');
day_type=1;
elseif n==3
fprintf('Tuesday, ');
day_type=1;
elseif n==4
fprintf('Wednesday, ');
day_type=1;
elseif n==5
fprintf('Thursday, ');
day_type=1;
elseif n==6
fprintf('Friday, ');
day_type=1;
elseif n==7
fprintf('Saturday, ');
day_type=2;
else
fprintf('Number must be from 1 to 7.n');
return
end
if day_type==1
fprintf('which is a week dayn');
else
fprintf('which is a weekend dayn');
end
Example 3: Nested if-statement
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2025-1-10 01:52
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社