0% found this document useful (0 votes)
3 views29 pages

MATLAB for Engineers Part 2

The document provides a comprehensive guide on using MATLAB for plotting functions, managing multiple data sets, and implementing flow control constructs. It covers topics such as creating plots, customizing line styles, using subplots, and basic fitting techniques, as well as flow control statements like if, switch, and loops. Additionally, it includes examples of exporting and loading data, creating menus, and defining functions in MATLAB.

Uploaded by

a196450
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)
3 views29 pages

MATLAB for Engineers Part 2

The document provides a comprehensive guide on using MATLAB for plotting functions, managing multiple data sets, and implementing flow control constructs. It covers topics such as creating plots, customizing line styles, using subplots, and basic fitting techniques, as well as flow control statements like if, switch, and loops. Additionally, it includes examples of exporting and loading data, creating menus, and defining functions in MATLAB.

Uploaded by

a196450
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/ 29

1

“We believe what we see”


or
“We see what we believe”

2
Creating a Plot

x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
Exercise
Now label the axes and add a title. The characters \pi
create the symbol p.

xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the Sine Function','FontSize',12)

3
Multiple Data Sets in One Graph

y2 = sin(x-.25);
y3 = sin(x-.5);
plot(x,y,x,y2,x,y3)

The legend command provides an easy way to


Exercise identify the individual plots.

legend('sin(x)','sin(x-.25)','sin(x-.5)')

4
Specifying Line Styles and Colors
plot(x,y,'color_style_marker')

color_style_marker is a string containing from one to four


characters (enclosed in single quotation marks) constructed
from a color, a line style, and a marker type:

• Color strings are 'c', 'm', 'y', 'r', 'g', 'b', 'w', and 'k'. These
correspond to cyan, magenta, yellow, red, green, blue, white,
and black.

• Linestyle strings are '-' for solid, '--' for dashed, ':' for
dotted, '-.' for dash-dot. Omit the linestyle for no line.

• The marker types are '+', 'o', '*', and 'x' and the filled
marker types 's‘ for square, 'd' for diamond, '^' for up triangle,
'v' for down triangle, '>‘for right triangle, '<' for left triangle, 'p'
for pentagram, 'h' for hexagram, and none for no marker.

5
Plotting Lines and Markers
If you specify a marker type but not a linestyle, MATLAB
draws only the marker. For example,

Exercise plot(x,y,'ks')

plots black squares at each data point, but does not connect
the markers with a line.

plot(x,y,'r:+')

plots a red dotted line and places plus sign markers at each
data point.

6
You may want to use fewer data points to plot the markers than
you use to plot the lines. This example plots the data twice
using a different number of points for the dotted line and
marker plots.

x1 = 0:pi/100:2*pi;
x2 = 0:pi/10:2*pi;
plot(x1,sin(x1),'r:',x2,sin(x2),'r+')
Exercise

7
Figure Windows
To make an existing figure window the current figure, you can
click the mouse while the pointer is in that window or you can
Exercise type

figure(n)

To open a new figure window and make it the current figure,


type

figure

8
Multiple Plots in One Figure
subplot(m,n,p)
partitions the figure window into an m-by-n matrix of small subplots and selects
the pth subplot for the current plot. The plots are numbered along first the top
row of the figure window, then the second row, and so on. For example, these
statements plot data in four different subregions of the figure window.

t = 0:pi/10:2*pi;
[X,Y,Z] = cylinder(4*cos(t));
subplot(2,2,1); mesh(X)
subplot(2,2,2); mesh(Y)
subplot(2,2,3); mesh(Z)
subplot(2,2,4); mesh(X,Y,Z)

9
Using Plot Editing Mode

10
Using the Property Editor

11
Basic Fitting

12
13
MATLAB has several flow control constructs:

• if statements
• switch statements
• for loops
• while loops
• continue statements
• break statements

14
if
The 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
Exercise statements. The groups of statements are delineated by the four
keywords – no braces or brackets are involved.

x = 2;
if x < 0 disp( ’neg’ ), else disp( ’non-neg’ ), end

15
bal = 10000;
if bal < 5000
rate = 0.09;
else
Exercise rate = 0.12;
end
newbal = bal + rate * bal;
disp( ’New balance after interest compounded is:’ )
format bank
disp( newbal )

16
bal = 15000;
if bal < 5000
rate = 0.09;
elseif bal < 10000
rate = 0.12;
Exercise else
rate = 0.15;
end
newbal = bal + rate * bal;
format bank
disp( ’New balance is:’ )
disp( newbal )

17
bal = 15000;
if bal < 5000
rate = 0.09;
end
if bal >= 5000 & bal < 10000
rate = 0.12;
Exercise end
if bal >= 10000
rate = 0.15;
end
newbal = bal + rate * bal;
format bank
disp( ’New balance is’ )
disp(newbal)
18
Using this form, instead of the elseif ladder, you can
make the following common mistake:

if bal < 5000


rate = 0.09;
end
if bal < 10000
Exercise rate = 0.12;
end
if bal >= 10000
rate = 0.15;
end

Can you see why you get the wrong answer (1120 instead
of 1090) if bal has the value 1000? When designing the
logic you need to make sure that one and only one of the
conditions will be true at any one time.
19
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.

d = floor(10*rand);
Exercise switch d
case {2, 4, 6, 8}
disp( ’Even’ );
case {1, 3, 5, 7, 9}
disp( ’Odd’ );
otherwise
disp( ’Zero’ );
end
20
Exporting text (ASCII) data
To export (save) the array in memory, let’s say

A = [1 2 3 ; 4 5 6]

Exercise save myData.txt A -ascii

If you view myData.txt in a text editor (or type it in the


Command Window) it looks like this:

1.0000000e+000 2.0000000e+000 3.0000000e+000


4.0000000e+000 5.0000000e+000 6.0000000e+000

21
The load command is the reverse of save. If the array A has
been saved in myData.txt as above the command

load myData.txt

creates a variable in the workspace with the same name as


the file, minus the extension, i.e. myData. If you don’t want
the filename as the variable name
Exercise
use the functional form of the command, e.g.

A = load(’myData.txt’)

Data imported in this way doesn’t have to be created by


MATLAB. You can create it in a text editor, or it could be
created by any other program that exports data in ASCII
format.

22
% Income tax the old-fashioned way
inc = [5000 10000 15000 30000 50000];
Exercise for ti = inc
if ti < 10000
tax = 0.1 * ti;
elseif ti < 20000
tax = 1000 + 0.2 * (ti - 10000);
else Taxable income Income tax
5000.00 500.00
tax = 3000 + 0.5 * (ti - 20000);
10000.00 1000.00
end;
15000.00 2000.00
disp( [ti tax] ) 30000.00 8000.00
end; 50000.00 18000.00
23
% Income tax the logical way
inc = [5000 10000 15000 30000 50000];
tax = 0.1 * inc .* (inc <= 10000);
tax = tax + (inc > 10000 & inc <= 20000) ...
.* (0.2 * (inc-10000) + 1000);
tax = tax + (inc > 20000) .* (0.5 * (inc-20000) +
3000);
disp( [inc’ tax’] );

24
Menus
k = 0;
while k ˜= 3
k = menu( ’Click on your option’, ’Do this’, ...
’Do that’, ’Quit’ );
if k == 1
Exercise disp( ’Do this ... press any key to continue ...’ )
pause
elseif k == 2
disp( ’Do that ... press any key to continue ...’ )
pause
end
end;

25
Note:
1. The menu function enables you to set up a
menu of choices for a user.

2. The value returned by menu (k here)


numbers the user’s choices.

3. You can design much more sophisticated


menu-driven applications with the MATLAB
GUIDE (Graphical User Interface Development
Environment).

26
Function M-files

Use the Editor to create and save (in the current MATLAB directory) the
function file f.m as follows:

function y = f(x)
y = xˆ3 + x - 3;
Exercise Then create and save another function file df.m :

function y = df(x)
y = 3*xˆ2 + 1;
Now write a separate script file, result.m in the same directory),

x = input( ’nilai x: ’ );
z = f(x)/df(x);
disp( [x f(x) df(x) z] )

27
Note:

You can use your own functions from the command


line, for example,
Exercise >> f(2)

should return 7 with f.m defined as above.

28
THANK YOU

29

You might also like