MATLAB Language Conditions IF condition


Conditions are a fundamental part of almost any part of code. They are used to execute some parts of the code only in some situations, but not other. Let's look at the basic syntax:

a = 5;
if a > 10    % this condition is not fulfilled, so nothing will happen

if a < 10    % this condition is fulfilled, so the statements between the if...end are executed
    disp('Not OK')


Not OK

In this example we see the if consists of 2 parts: the condition, and the code to run if the condition is true. The code is everything written after the condition and before the end of that if. The first condition was not fulfilled and hence the code within it was not executed.

Here is another example:

a = 5;
if a ~= a+1        % "~=" means "not equal to"
    disp('It''s true!') % we use two apostrophes to tell MATLAB that the ' is part of the string

The condition above will always be true, and will display the output It's true!.

We can also write:

a = 5;
if a == a+1    % "==" means "is equal to", it is NOT the assignment ("=") operator

This time the condition is always false, so we will never get the output Equal.

There is not much use for conditions that are always true or false, though, because if they are always false we can simply delete this part of the code, and if they are always true then the condition is not needed.