You are on page 1of 28

December 4, 2009

Where do we go from
here?
So far we have used Matlab in two ways:
As a scratch pad in the command window
To write simple programs (scripts) in the editing
window
In both of these, we assumed that the programmer
was the user
Now we will move on to more complicated
techniques for use when the user and programmer
are different people
Allow input/output techniques
Logic for decision making
5.2.1 User-Defined Input
We can create more general programs by
allowing the user to input values

z = input(‘Enter a value’)
% Displays Enter a value to the screen
% If the user enters 5 at the prompt, then z = 5

z = input(‘Enter values for z in brackets’)


% User enters [1, 2, 3; 4, 5, 6]

z = 1 2 3
4 5 6
5.2.2 Output Options
The disp() function has the format of
disp(‘message’)
disp(variable)

To combine text and numbers on one line, you


need to make a string out of the numbers with
the num2str() function:
disp([‘The value was: ’ num2str(variable)])
fprintf()
General format: fprintf(format_string, var, …)

temp = 98.6;
fprintf(‘The temperature is %f degrees F \n’, temp)

%f is the place holder for the variable “temp”


Placeholders and their meanings:
%f – fixed point (decimal)
%e – exponential notation
%g – whichever is shorter, %f or %e
fprintf()
We can also make this more precise:

temp = 98.6;
fprintf(‘The temperature is %8.2f degrees F \n’, temp)

% this will print 98.60

%8.2f – “8” is in the width field, “2” is in the


precision field
There are 8 total spaces to print, and 2 of those
spaces will be after the decimal point
fprintf()
Print multiple values and literal text to the
screen:

B = [8.8 7.7 ;
8800 7700];
fprintf('X is %4.2f meters or %8.3f mm\n', 9.9, 9900, B)

MATLAB displays:
X is 9.90 meters or 9900.000 mm
X is 8.80 meters or 8800.000 mm
X is 7.70 meters or 7700.000 mm 
Questions???
5.3 Functions in Matlab
The following would be in its own separate M-file:

function output = g(x,y)


%This function multiplies x and y together
% Be sure that x and y are the same size matrices
a = x .* y;
output = a;

Variable “a” is local to the function


The function is called “g”
The M-file would have be called “g.m”
5.4 Control Structures
Sequences, selection structures, repetition
structures
This will work very much the same way as the
do in C++
We of course will need RELATIONAL and
LOGICAL operators:
Relational: <, <=, >, >=, ==(equal), ~=(not
equal)
Logical: &(and), ~(not), |(or)
Logical operations
As with arithmetic operators, logical operators
can be performed collectively on the
individual components of 2 matrices as long
as:
both matrices are the same size, or
one of the values is a scalar

The result will be a vector of logical values


with the same length as the original vector(s)
Logical operations
>> A = [2 5 7 1 3];
>> B = [0 6 5 3 2];
>> A >= 5
ans =
0 1 1 0 0
>> A >= B
ans =
1 0 1 0 1
>> C = [1 2 3]
>> A > C
??? Error using ==> gt
Matrix dimensions must agree.
Logical operations
We can make more complex operations using
AND and OR:
&, | operate on logical arrays of matching size
 Element-by-element
&&, || combine logical results and are
associated with short-circuiting conditional
statements
Logical operations
(continued)
>> A = [true true false false];
>> B = [true false true false];
>> A & B
ans =
1 0 0 0
>> A | B
ans =
1 1 1 0
>> C = [1 0 0];
>> A & C
??? Error using ==> and
Matrix dimensions must agree.
5.4.2 Conditional
Execution
Basic conditional execution
requires two things:
A logical expression, and
A code block
If the expression is true, the
code block is executed.
Otherwise, execution is resumed
at the instruction following the
code block
Compound conditionals

By introducing elseif and else, we allow for the


possibility of either conditional or unconditional
execution when a test returns false as illustrated.
if Statements
The general template for if statements is:
if <logical expression 1>
<code block 1>
elseif <logical expression 2>
<code block 2>
.
.
.
elseif <logical expression n>
<code block n>
else
<default code block>
end
Logical Expressions
Can be created in the following ways:
Boolean constant (true or false)
Variable containing a boolean result (found)
Logical operation result (A > 5)
Logically negating a boolean quantity (~found) ~, not
-!
Combining logical expressions (A && B, A || B)
Matlab functions that are the logical equivalent of &&, ||,
and ~ operators (and(A, B), or(A, B), not(A))
Matlab functions that operate on Boolean vectors
(any(…), all(…))
General Observations
A logical expression is any statement that
returns a logical result.
While indentation has no effect on the logical
flow, it helps to clarify the logical flow. The
MATLAB editor automatically creates suitable
indentation as you type.
Find Function
Another selection structure is the “find”
function
It returns a vector composed of all the indices
of the nonzero elements of a vector x:

temp = [100, 98, 94, 101, 93]


find(temp<95)
ans = 3 5

[row, column] = find(expression)


5.4.3 Iteration in General
Iteration allows controlled repetition of a code block.
Control statements at the beginning of the code block
specify the manner and extent of the repetition:
 The for loop is designed to repeat its code block a fixed
number of times and largely automates the process of
managing the iteration.
 The while loop is more flexible in character. Its code block
can be repeated a variable number of times. It is much
more of a “do-it-yourself” iteration kit.

Note, however that Matlab is designed to avoid iteration.


The array processing operations make do-it-yourself
iteration unnecessary
for Loops
The template for a for loop is:
for <variable> = <vector>
<code block>
end
The for loop automatically sets
the value of the variable to
each element of the vector in
turn and executes the code
block with that value.
while Loops
The code block will be repeated
as long as the logical expression
returns true.

The while loop template is:


<initialization>
while <logical expression>
<code block>
% must make some changes
% to enable the loop to terminate
end
Engineering Example
Given a tank as shown, how do
you calculate the volume of
liquid? The answer of course is
“it depends on h.”
If h <= r, do one calculation;
otherwise if h < (H-r) do a
second;
Otherwise if h <= H, do a third;
Otherwise there is an error!
The Solution
if h < r
v = (1/3)*pi*h.^2.*(3*r-h);
elseif h < H-r
v = (2/3)*pi*r^3 + pi*r^2*(h-r);
elseif h <= H
v = (4/3)*pi*r^3 + pi*r^2*(H-2*r) ...
- (1/3)*pi*(H-h)^2*(3*r-H+h);
else
disp(‘liquid level too high’)
continue
end
fprintf( ...
'rad %0.2f ht %0.2f level %0.2f vol %0.2f\n', ...
r, H, h, v);
switch Statements
The template for a switch statement is:
switch <parameter>
case <case specification 1>
<code block 1>
case <case specification 2>
<code block 2>
.
.
case <case specification n>
<code block n>
otherwise
<default code block>
end
General Observations
The switch statement is looking for the
parameter to have an exact match to one of
the cases.
One case specification may have multiple
values enclosed in braces( {…}).
The default case catches any values of the
parameter other than the specified cases.
The default case should trap bad parameter
values.

You might also like