0% found this document useful (0 votes)
13 views

what

damn son where did u find this §

Uploaded by

theoneandtheonly
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

what

damn son where did u find this §

Uploaded by

theoneandtheonly
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Chapter 4: Programming

I. Flow Control
If
he if statement evaluates a logical expression and executes a group of statements when the expression is true. The
optional elseif and else keywords provide for the execution of alternate groups of statements. An end keyword, which
matches the if, terminates the last group of statements.
Example 1: Example 2:
if rem(n,2) ~= 0 Write a matlab code which
M = odd_magic(n) compare two matrices A anb B
elseif rem(n,4) ~= 0 element by element and write
M = single_even_magic(n) one of the following
else corresponding results : greater,
M = double_even_magic(n) less, equal, Unexpected
end situation

1
switch and case
The switch statement executes groups of statements based on the value of a variable or expression. The keywords case
and otherwise delineate the groups. Only the first matching case is executed. There must always be an end to match
the switch.
Note: Unlike the C language switch statement, MATLAB switch does not fall through. If the first case statement is true,
the other case statements do not execute. So, break statements are not required.

Example 3:
switch (rem(n,4)==0) + (rem(n,2)==0)
case 0
M = odd_magic(n)

case 1
M = single_even_magic(n)

case 2
M = double_even_magic(n)

otherwise
error('This is impossible')
end

2
for
The for loop repeats a group of statements a fixed, predetermined number of times. A matching end delineates the
statements.

Example 4: Example 5:
for n = 3:32 for i = 1:m
r(n) = rank(rand(n)); for j = 1:n
end H(i,j) = 1/(i+j);
r end
end

while
The while loop repeat statements an indefinite number of times. The general form of a while statement is:

while expression
statements
end

The statements are executed while the expression has all non-zero elements.

3
continue
The continue statement passes control to the next iteration of the for loop or while loop in which it appears, skipping any
remaining statements in the body of the loop. In nested loops, continue passes control to the next iteration of the for
loop or while loop enclosing it.

Example 6:
Display the multiples of 7 from 1 through 50 using for loop, if and continue statements.
The results have to be shown in the following manner:

Divisible by 7: 7
Divisible by 7: 14
Divisible by 7: 21
Divisible by 7: 28
Divisible by 7: 35
Divisible by 7: 42
Divisible by 7: 49

4
break
break terminates the execution of FOR and WHILE loops. In nested loops, break exits from the innermost loop only and
also break is not defined outside of a FOR or WHILE loop.
try - catch
The general form of a try-catch statement sequence is
try
statement
...
statement

catch
statement
...
statement

end

In this sequence the statements between try and catch are executed until an error occurs. The statements between
catch and end are then executed. If an error occurs between catch and end, MATLAB terminates execution unless
another try-catch sequence has been established.

5
Example 7:
Create two matrices that you cannot concatenate vertically.
1. Concatenate both matrices vertically and show the result.

2. Replace the error message by another message showing more information about the dimensions.

return
return terminates the current sequence of commands and returns control to the invoking function or to the keyboard.
return is also used to terminate keyboard mode. A called function normally transfers control to the function that
invoked it when it reaches the end of the function. You can insert a return statement within the called function to force
an early termination and to transfer control to the invoking function.

Example 8:
In your current working folder, create a function, findSqrRootIndex, to find the index of the first occurrence of the
square root of a value within an array. If the square root isn't found, the function returns NaN.

6
II. Other Data Structures
Multidimensional Arrays
Multidimensional arrays in MATLAB are arrays with more than two subscripts. One way of creating a multidimensional
array is by calling zeros, ones, rand, or randn with more than two arguments. For example,
R = randn(3,4,5);
creates a 3-by-4-by-5 array with a total of 3x4x5 = 60 normally distributed random elements.

Example 1:
Show how to enter manually a 3-by-3-by-4 array M which contains the values 1, 2, 3, …, 36 arranged by rows.

Example 2:
Repeat example 1:
(i) using for loops,
(ii) using reshape command.

Example 3:
(i) Create an array A which gather each two successive pages of the previous array M one bellow the other. 7
(ii) Calculate the sum of the last elements of each matrix composing the array M.
(iii) Create a row vector V wchich contains the first element of each matrix composing the array M.
(iv) What is sum(M)

Cell Arrays
Cell arrays in MATLAB are multidimensional arrays whose elements are copies of other arrays. A cell array of empty
matrices can be created with the cell function. Cell arrays are created by enclosing a miscellaneous collection of things
in curly braces, {}. The curly braces are also used with subscripts to access the contents of various cells.
For example,
A=magic(4)
C = {A sum(A) prod(prod(A))}
produces a 1-by-3 cell array. The three cells contain the magic square, the row vector of column sums, and the product
of all its elements.

The first two cells are too large to print in the limited space, but the third cell contains only a single number. So there is
room to print it in the Command Window.
To retrieve the contents of one of the cells, use subscripts in curly braces. For example, C{1} retrieves the magic square
and C{3} is 16!.

8
Example: What would be the result of the matlab code shown bellow ?

M = cell(8,1);
for n = 1:8
M{n} = magic(n);
end
M

It produces a sequence of magic


squares of different order.
M=
[ 1]
[2×2 double]
[3×3 double]
[4×4 double]
[5×5 double]
[6×6 double]
[7×7 double]
[8×8 double]
9
It has also produced three-
dimensional arrays to store a
sequence of matrices of
different sizes.

10
Characters and Text
Enter text into MATLAB using single quotes. For example,
s = 'Hello’
Creates a a 1-by-5 character array.

Internally, the characters are stored as numbers The statement


a = double(s)
converts the character array to a numeric matrix containing floating-point representations of the ASCII codes for each
character. The result is
a=
72 101 108 108 111

The statement
s = char(a)
reverses the conversion.

The printable characters in the basic ASCII character set are represented by the integers 32:127.

Example:
- Show in the command window the printable characters in a 16 by 6 matrix,
- then show the characters in a bigger size by varying the font being used in the Command Window.

11
Concatenation with square brackets joins text variables together into larger strings. The statement
h = [s, ' world’]

joins the strings horizontally and produces


h=
Hello world

The statement
v = [s; 'world']

joins the strings vertically and produces


v=
Hello
world

Note that a blank has to be inserted before the 'w' in h and that both words in v
have to have the same length. The resulting arrays are both character arrays; h is
1-by-11 and v is 2-by-5. A
line
can
Question:
be
How can we manipulate a body of text containing lines of different lengths ?
defined
using
two
12
points.
you have two choices: (i) a padded character array or (ii) a cell array of strings. When creating a character array, you
must make each row of the array the same length. (Pad the ends of the shorter rows with spaces.) The char function
does this padding for you. For example,

S = char('A’,’line’,’can’,’be’,’defined’,’using’,’two’,’points.’)

produces a 5-by-9 character array.

S=
A
line
can
be
defined
using
two
points.

Alternatively, you can store the text in a cell array. For example,

C = {’A’;’line’;’can’;’be’;’defined’;’using’;’two’;’points.’}

creates a 5-by-1 cell array that requires no padding because each row of the array can have a different length.
13
Structures
Structures are multidimensional MATLAB arrays with elements accessed by textual field designators. For example,

S.name = ’name1’;
S.score = 13;
S.grade = ‘B-'

creates a scalar structure with three fields.


S=
name: ‘name1'
score: 13
grade: ‘B-’

Like everything else in MATLAB, structures are arrays, so you can insert additional elements. In this case, each element
of the array is a structure with several fields. The fields can be added one at a time,

S(2).name = ’name2';
S(2).score = 18;
S(2).grade = ’A’;

or an entire element can be added with a single statement.

S(3) = struct('name’,’name3','score’,’16’,'grade',’B+')
14
>> S.score >> [S.score] >> S.name >> {S.name} >> char(S.name)
ans = ans = ans = ans = ans =
83 83 91 70 name1 1×3 cell array name1
ans = ans = ‘name1' ‘name2' ‘name3' name2
91 name2 name3
ans = ans =
70 name3

Example:

Create three structures which contains three students and fill them according to the following table.

Number Score Grade Observation


Name 1 3 12 B- Admitted
Name 2 6 15 B+ Admitted
Name 3 18 00 F Failed

15
III. Scripts and Functions
MATLAB is a powerful programming language as well as an interactive computational environment. Files that contain
code in the MATLAB language are called M-files. You create M-files using a text editor, then use them as you would any
other MATLAB function or command.

There are two kinds of M-files:


• Scripts, which do not accept input arguments or return output arguments. They operate on data in the workspace.
• Functions, which can accept input arguments and return output arguments. Internal variables are local to the
function.

Scripts
When you invoke a script, MATLAB simply executes the commands found in the file. Scripts can operate on existing
data in the workspace, or they can create new data on which to operate. Although scripts do not return output
arguments, any variables that they create remain in the workspace, to be used in subsequent computations. In
addition, scripts can produce graphical output using functions like plot.

For example, create a file called magicrank.m that contains these MATLAB commands.

for n = 1:32
r(n) = rank(magic(n));
end
r
16
bar(r)
To to execute the commands, Click on Run of the script M file or Type the name of the M file in the Command Window.

Functions
Functions are M-files that can accept input arguments and return output arguments. The names of the M-file and of
the function should be the same. Functions operate on variables within their own workspace, separate from the
workspace you access at the MATLAB command prompt.

A good example is provided by rank. The M-file rank.m is available in the directory:
toolbox/matlab/matfun

You can see the file with the command:


type rank

The first line of a function M-file starts with the keyword function. It gives the function name and order of arguments.
In this case, there are up to two input arguments and one output argument.
The next several lines, up to the first blank or executable line, are comment lines that provide the help text. These lines
are printed when you type help rank.

The rest of the file is the executable MATLAB code defining the function. The variable s introduced in the body of the
function, as well as the variables on the first line, r, A and tol, are all local to the function; they are separate from any
variables in the MATLAB workspace.

17
This example illustrates one aspect of MATLAB functions that is not ordinarily found in other programming languages: a
variable number of arguments.
If the second input argument is not supplied, the function computes a default value. Within the body of the function,
two quantities named nargin and nargout are available which tell you the number of input and output arguments
involved in each particular use of the function.
Note: If you duplicate function names, MATLAB executes the one that occurs first in the search path.
Example:
(i) Write a matlab function wich calculate the factorial of a positive integer.
(ii) Another function which calculate the exponential of a real number.

Types of Functions: (i) Anonymous Functions, (ii) Primary functions and (iii) Private Functions
Anonymous Functions
An anonymous function is a simple form of MATLAB function that does not require an M-file. It consists of a single
MATLAB expression and any number of input and output arguments. You can define an anonymous function right at
the MATLAB command line, or within an M-file function or script. This gives you a quick means of creating simple
functions without having to create M-files each time.

The syntax for creating an anonymous function from an expression is


Function_name = @(arglist) expression of the function.
18
Example:

Create a matlab script which :

(i) Define an anonymous function 𝑔 𝑥, 𝑦 = 𝑥2 + 𝑦2 ,

(ii) Calculate module11 = g(1,1)

(iii) Calculate module12 = g(1,2)

19
Primary functions:
All functions that are not anonymous must be defined within an M-file. Each M-file has a required primary function
that appears first in the file, and any number of subfunctions that follow the primary. Primary functions can be invoked
from outside of their M-file (from the MATLAB command line or from functions in other M-files)

The exponentielle_Re and factoriel_nat functions of the previous exapmle are primary functions.

Private Functions
A private function is a type of primary M-file function. Its unique characteristic is that it is visible only to a limited
group of other functions. This type of function can be useful if you want to limit access to a function, or when you
choose not to expose the implementation of a function. Private functions reside in subdirectories with the special
name private. They are visible only to functions in the parent directory. Because private functions are invisible outside
the parent directory, they can use the same names as functions in other directories. This is useful if you want to create
your own version of a particular function while retaining the original in another directory.

Global Variables
If you want more than one function to share a single copy of a variable, simply declare the variable as global in all the
functions. Do the same thing at the command line if you want the base workspace to access the variable. The global
declaration must occur before the variable is actually used in a function.

20
Example:

% Function falling % Script


function h = falling(t) global GRAVITY
global GRAVITY GRAVITY = 9.8;
h = 1/2*GRAVITY*t.^2; y = falling((0:.1:5)');

21

You might also like