haibaraxx的个人博客分享 http://blog.sciencenet.cn/u/haibaraxx

博文

Matlab: if statement

已有 2730 次阅读 2016-8-20 03:34 |个人分类:Matlab|系统分类:科研笔记| elseif

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




https://blog.sciencenet.cn/blog-3031432-997507.html

上一篇:Matlab: input & fprintf
下一篇:Matlab: create arrays of all zeros and ones
收藏 IP: 134.1.1.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-10-20 09:21

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部