Skip to main content

11.5) if...elseif...else...end Statement: Examples


[matlab]
>> % Separately add up all odd and even numbers within the range 1 to 100
>> odd_sum=0;
>> even_sum=0
>> for i=1:100
>> if (mod(i,2)==0)
>> even_sum=even_sum+i;
>> else
>> odd_sum=odd_sum+i;
>> end
>> end
[/matlab]

Why don't we require an elseif statement here?

[matlab]
>> % Use the if...elseif...else...end to output different
>> % plots according to a user-defined parameter
>> % plot_type=1 then line plot
>> % plot_type=2 then scatter plot
>> plot_type=2
>> data=1:100;
>> data(2,:)=rand(1,100);
>> if (plot_type==1)
>> scatter(data(1,:),data(2,:))
>> elseif (plot_type==2)
>> line(data(1,:),data(2,:))
>> else
>> display('plot type unknown')
>> end
[/matlab]
[matlab]
>> % Check if a variable you have just calculated is equal to pi
>> a=3.1416
>> if (a==pi)
>> display('value equal to pi')
>> else
>> display('value not equal to pi')
>> end
[/matlab]

Can you explain the result?