Matlab® programming is a very useful tool for engineers or mathematicians to calculate or solve very complex mathematical problems. In this programming language, you can use general coding characteristics such as ‘if-else’. In this article, we will explain how to use ‘if-else’ in Matlab®.
How To Use ‘If-Else’ In MatLab® Programming?
>> for a = [5 13 -1] if( a>10) disp([int2str(a) '- number a is greater than 10']) elseif a < 0 disp([int2str(a) '- number a is lower than 10']) else disp([int2str(a) '- number a is between 0 and 10']) end end 5- number a is between 0 and 10 13- number a is greater than 10 -1- number a is lower than 10 >>
We want to explain the if-else in Matlab® with a very basic example as above. If you want much more complex examples and explanations about if-else in Matlab®, inform us about it in the comments below.
We have created a ‘for’ loop and a vector. In each step of this for loop in Matlab®, the elements of this vector will be assessed by if-else codes inside the ‘for’ loop. On every loop, ‘a’ will have different values. According to these values, a will be displayed according to its situation.
In the first ‘if’ code, ‘a’ will be displayed if it is bigger than 10 as shown by the green arrow above. So we typed a ‘condition’ as a>10 near of ‘if’.
Take a look at the ‘elseif’, we put the condition of ‘a<0’ and ‘a’ will be displayed if the condition is valid for the value of ‘a’ in the current loop.
‘Else’ means, the other conditions except for the above conditions in ‘if’ and ‘elseif’. For this example, else means the number of ‘a’ is between 0 and 10.
As you can see above, all the numbers in the loop vector are displayed according to their condition inside the ‘if-else’ code in Matlab®.
So the logic of ‘if-else’ is like that in Matlab® programming.
Do not forget to leave your comments and questions below about the use of ‘if-else’ in Matlab® below.
If you want further coding examples about ‘if-else’ in Matlab®, inform us in the comments.
This article is prepared for completely educative and informative purposes. Images used courtesy of Matlab®
Your precious feedbacks are very important to us.