Computer

Introduction to MATLAB Tutorial: Control Flow and Operations

Introduction to MATLAB Tutorial: Control Flow and Operations
In this guide
  1. Introduction
  2. Control Flow
  3. Saving Output to a File

Introduction to MATLAB: you can find the full MATLAB tutorial series here. In this tutorial, we will discuss control flow and operations in MATLAB.

Introduction

MATLAB is also a programming language. Like other programming languages, MATLAB has decision-making structures that control how commands are executed. These decision-making or control flow structures include for loops, while loops, and if-else-end constructions. Control flow structures are often used in script M-files and function M-files.

By creating a file with the extension .m, we can easily write and run programs. We do not need to compile the program, since MATLAB is an interpreted (not compiled) language. MATLAB has thousands of functions, and you can add your own using M-files.

MATLAB provides several tools to control the flow of a program (script or function). In a simple program, as shown in the previous chapter, the commands are executed one after the other. Here we introduce the flow control structures that make it possible to skip commands or to execute a specific group of commands.

Control Flow

MATLAB has four control flow structures: the if statement, the for loop, the while loop, and the switch statement.

The “if…end” Structure

MATLAB supports these variants of the “if” construct:

• if … end

• if … else … end

• if … elseif … else … end

The simplest form of the if statement is:

if expression

statements

end

Here are some examples based on the familiar quadratic formula.

1.

discr = b*b - 4*a*c;

if discr < 0

disp('Warning: discriminant is negative, roots are imaginary');

end

2.

discr = b*b - 4*a*c;

if discr < 0

disp('Warning: discriminant is negative, roots are imaginary');

elseif discr == 0

disp('Discriminant is zero, roots are repeated')

else

disp('Roots are real')

end

Note that:

• elseif has no space between else and if (it is one word)

• no semicolon (;) is needed at the end of lines containing if, else, or end

• indenting the if block is not required, but it makes the code easier to read

• the end statement is required

Relational and Logical Operators

A relational operator compares two numbers and determines whether the comparison is true or false. The relational operators are shown below:

Note that the “equal to” relational operator consists of two equal signs (==) with no space between them, since = is reserved for the assignment operator.

The “for…end” Loop

In the for … end loop, a command is executed repeatedly a fixed, predetermined number of times. The syntax is:

for variable = expression

statements

end

Usually, the expression is a vector of the form i:s:j. A simple example of a for loop is:

for ii=1:5

x=ii*ii

end

It is a good idea to indent loops for readability, especially when they are nested. Note that the MATLAB editor does this automatically.

Multiple for loops can be nested, in which case indentation helps readability. The following statements form the 5-by-5 symmetric matrix A with (i, j) element i/j for j ≥ i:

n = 5;

A = eye(n);

for j=2:n

for i=1:j-1

A(i,j)=i/j;

A(j,i)=i/j;

end

end

The “while…end” Loop

This loop is used when the number of passes is not specified. The looping continues until a stated condition is satisfied. The while loop has the form:

while expression

statements

end

The statements are executed as long as the expression is true.

x = 1

while x <= 10

x = 3*x

end

Note that if the condition inside the loop is not well defined, the loop will continue indefinitely. If this happens, you can stop the execution by pressing Ctrl-C.

Other Flow Structures

• The break statement: a while loop can be terminated with the break statement, which passes control to the first statement after the corresponding end. The break statement can also be used to exit a for loop.

• The continue statement can be used in a for loop to pass immediately to the next iteration of the loop, skipping the remaining statements in the loop.

• Other control statements include return, continue, switch, and more. For details about these commands, consult the MATLAB documentation.

Operator Precedence

We can build expressions that use any combination of arithmetic, relational, and logical operators. Precedence rules determine the order in which MATLAB evaluates an expression. We have already seen this in the “Tutorial Lessons”.

Here we add other operators to the list. The precedence rules for MATLAB are shown in the table below, ordered from the highest (1) to the lowest (9) precedence level. Operators are evaluated from left to right.

Saving Output to a File

Besides displaying output on the screen, the fprintf command can be used to write output to a file. The saved data can later be used by MATLAB or other software.

Saving the results of a computation to a text file takes the following steps:

1. Open a file using fopen

2. Write the output using fprintf

3. Close the file using fclose

Here is an example (script) of its use.

% write some variable length strings to a file

op = fopen('weekdays.txt','wt');

fprintf(op,'Sunday\nMonday\nTuesday\nWednesday\n');

fprintf(op,'Thursday\nFriday\nSaturday\n');

fclose(op);

This file (weekdays.txt) can be opened with any program that can read .txt files.

You can see the complete MATLAB tutorial here:

  1. Introduction to MATLAB
  2. Chapter 2 on MATLAB
  3. Matrix in MATLAB
  4. Array and Linear Operations in MATLAB
  5. Programming in MATLAB
  6. Control Flow and Operations in MATLAB
  7. Debugging M-files in MATLAB

Written by

ABHIYAN

Published on TheTechRim in Computer.