Programming in Matlab

Matlab → Script → Function → Matlab Programming

The if-else conditions
The if / else conditions are used to make basic decisions in a program. In Matlab, the construction of if-end condition is given as follows.

Construction: if-end structure

if condition
statement;
end

In the next example, a script is written where the user is asked to insert a number and if the number is greater than 10, it displays, “The number is greater than 10” and does nothing otherwise. Suppose the script is saved with the name Example1.

a = input('Enter a number: ');
if a>10
disp('The number is greater than 10');
end

In Command Window
>> Example1
Enter a number: 12
The number is greater than 10
>> Example1
Enter a number: 7

NOTE: The program does nothing when the inserted number is 10 or less than 10.

Construction: if-else-end structure

if condition
statement;
else
statement;
end

In the next example, we use the if-else-end structure to write a script where the user is asked to insert a number and if the number is greater than 10, it displays, “The number is greater than 10”, else it displays, “The number is less than or equal to 10”. Suppose the script is saved with the name Example2.

a = input('Enter a number: ');
if a>10
disp('The number is greater than 10');
else
disp('The number is less than or equal to 10')
end

In Command Window
>> Example2
Enter a number: 12
The number is greater than 10
>> Example2
Enter a number: 7
The number is less than or equal to 10

Construction: if-elseif-else-end structure

if condition
statement;
elseif condition
statement;
else
statement;
end

In the next example, we use the if-elseif-else-end structure to write a script where the user is asked to insert a number and if the number is greater than 10, it displays, “The number is greater than 10”, And, if the number is 10, it displays, “The number is 10”, else it displays, “The number is less 10”. Suppose the script is saved with the name Example3.

a = input('Enter a number: ');
if a>10
disp('The number is greater than 10');
elseif a==10
disp('The number is 10');
else
disp('The number is less than 10')
end

In Command Window
>> Example3
Enter a number: 11
The number is greater than 10
>> Example3
Enter a number: 5
The number is less than 10
>> Example3
Enter a number: 10
The number is 10

When a number is divided by 2 and the remainder is 0, it is called an even number and odd otherwise. The program to determine whether a number is even or odd can be written as,

number = input('Please enter a number: ');
if rem(number,2)==0
disp('The number is even.');
else
disp('The number is odd.');
end

In Command Window
>> evenOdd NOTE: The program is saved with the name evenOdd.
Enter a number: 18
The number is even.
>> evenOdd
Enter a number: 1357
The number is odd.