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

Ch02 - MATLAB Basics (Part 2)

Uploaded by

dgdzheng
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Ch02 - MATLAB Basics (Part 2)

Uploaded by

dgdzheng
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

MATLAB Programming for Engineers

Ming Jiang

www.wcomms.com
Chapter 2: MATLAB Basics
(Part 2)

Ming Jiang

www.wcomms.com
MATLAB Programming for Engineers
Chapter 2: MATLAB Basics (Part 2)

• Scalar and Array Operations


• Hierarchy of operations
• Built-in MATLAB functions
• Basics of plotting
• Debugging MATLAB

Ming Jiang
Scalar Operations

Example 2 ^ ((8+2)/5) = 2 ^ (10/5)


= 2 ^ 2
= 4

Ming Jiang www.wcomms.com 4


Array and Matrix Operations
Array and Matrix Operations
Example 1 (1/2)

Example 1a
(a) a + b =

(b) a .* b =

(c) a * b = Only
supported
by latest
(d) a * c = versions

(e) a + c = 4 3
4 3
(f) a + d =

(g) a .* d =

(h) a * d =

Ming Jiang www.wcomms.com 7


Example 1 (2/2)

(i) d ./ a = (m) a \ d =
Example 1b ans = Error using \ Scalar
5.0000 Inf Matrix dimensions
2.5000 5.0000 must agree.

(j) d .\ a = (n) inv(a) * d =


ans = ans =
0.2000 0 5 0
0.4000 0.2000 -10 5
(k) d / a = (o) a .^ d =
Error using / ans =
Matrix dimensions 1 0
must agree. 32 1
(l) d \ a = (p) d .^ a =
ans = ans =
0.2000 0 5 1
0.4000 0.2000 25 5

Ming Jiang www.wcomms.com 8


Example 2

Example 2: Given the constants aij and bk , calculate xn

xn = ?

Ming Jiang www.wcomms.com 9


Example 2

Example 2: Given the constants aij and bk , calculate xn

X = A \ B

Ming Jiang www.wcomms.com 10


MATLAB Programming for Engineers
Chapter 2: MATLAB Basics (Part 2)

• Scalar and Array Operations


• Hierarchy of operations
• Built-in MATLAB functions
• Basics of plotting
• Debugging MATLAB

Ming Jiang
Hierarchy of Operations

Operations' Precedence
• The contents of all parentheses are evaluated, starting from the
innermost parentheses and working outward
• All exponentials are evaluated, working from left to right
• All multiplications and divisions are evaluated, from left to right
• All additions and subtractions are evaluated, from left to right

Example >> 7*3-5^3/7

ans = Use parentheses


3.1429 to make your
equations clear
>> 7*3-5^(3/7) and easy to
understand
ans =
19.0068

Ming Jiang www.wcomms.com 12


MATLAB Programming for Engineers
Chapter 2: MATLAB Basics (Part 2)

• Scalar and Array Operations


• Hierarchy of operations
• Built-in MATLAB functions
• Basics of plotting
• Debugging MATLAB

Ming Jiang
Built-in MATLAB Functions (1/2)

What is a Function
• Function = an expression that accepts one or more
input values and calculates the results from them
• Functions for scientific and technical calculations
are more complex than +, -, *, \, ^ operations

Examples of Functions
• Commonly used function examples:
• Trigonometric functions, logarithms, square roots, etc.
• Rarer functions examples specific to a single or a few problems
• Hyperbolic functions, Bessel functions, etc.

What MATLAB offers


• One of MATLAB's greatest strengths is that it comes with
an incredible variety of built-in functions ready for use

Ming Jiang www.wcomms.com 14


Built-in MATLAB Functions (2/2)

• Some MATLAB functions can return


more than one result

Example
>> maxval = max ([1 -5 6 -3])
maxval =
6

>> [maxval index] = max ([1 -5 6 -3])


maxval =
6
index =
3

Ming Jiang www.wcomms.com 15


Using MATLAB Functions with Array Inputs

• Functions receiving an array of input values


will calculate an array of output values

Example

>> x = [ 0 pi/2 pi 3*pi/2 2*pi]

x =
0 1.5708 3.1416 4.7124 6.2832

>> y = sin(x)

y =
0 1.0000 0.0000 -1.0000 -0.0000

Ming Jiang www.wcomms.com 16


Common MATLAB Functions (1/5)

Ming Jiang www.wcomms.com 17


Common MATLAB Functions (2/5)

Examples >> x.^3


ans =
% e  2.718281828 1 8 27
(Euler's number)
>> exp(3) >> power(x,3)
ans = ans =
20.0855 1 8 27

>> 2^3
Cannot execute the >> power([1 2 3],[1 2 3])
ans =
math operation with ans =
8
non-square matrix 1 4 27
>> x = [1 2 3]
>> log2([1 2 4]) = ?
>> x^3 = ?
>> log10([1 10 100]) = ?
Error using ^
ans =
Inputs must be a scalar
0 1 2
and a square matrix.

Ming Jiang www.wcomms.com 18


Common MATLAB Functions (3/5)

 n 2 3
Examples x x x
ex    1 x   
n  0 n! 2! 3!
>> k = 2;
>> B = [1 2; 3 4]  n 2 3
X X X
B = 1 2 eX    1 X   
3 4 n  0 n! 2! 3!
>> k.^B = ?
ans = 2 4 Bln k
8 16 k  (e )  e
B ln k B Square
Matrix

>> k^B = ?
ans = >> k^B = expm(B*log(k))
10.4827 14.1519
21.2278 31.7106

Ming Jiang www.wcomms.com 19


Common MATLAB Functions (4/5)

Ming Jiang www.wcomms.com 20


Common MATLAB Functions (5/5)

Examples >> int2str(2)


ans =
2

>> str2num('3.1415926')
ans =
3.1416

>> format long, str2num('3.1415926')


ans =
3.141592600000000

>> str2num('who are u?') = ?


str2num('who are u?')
|
Error: The input character is not valid in MATLAB
statements or expressions.

Ming Jiang www.wcomms.com 21


MATLAB Programming for Engineers
Chapter 2: MATLAB Basics (Part 2)

• Scalar and Array Operations


• Hierarchy of operations
• Built-in MATLAB functions
• Basics of plotting
• Debugging MATLAB

Ming Jiang
Introduction to Plotting

Why do we love MATLAB?

• Because it plots EVERYTHING!


• Extensive, device-independent
plotting capability
• Very easy to plot any data at any
time

>> spy = ?

Ming Jiang www.wcomms.com 23


Drawing Simple XY Plots

Two steps to plot a data set


• Create two vectors containing the x and y values to be plotted
• Then use the plot function!

Example
x = 0:1:10;
y = x.^2 - 10.*x + 15;
plot(x,y);
title('Example Plot');
ylabel('y');
xlabel('x');
grid on;

Ming Jiang www.wcomms.com 24


Printing a Plot

The print command


print <options> <filename>
• If no filename is included, it prints the current
figure on the system printer
• If a filename is specified, the command prints the
current figure to the specified file

• It is a powerful command supports lots of


functionalities
• Use help print to find out more options

Ming Jiang www.wcomms.com 25


Exporting a Plot as a Graphical Image (1/2)

Specify the format of the output


Provides a
Example run-time facility
print -djpeg98 example.jpg for graph saving
• Creates a JPEG image of the current
figure at a quality level of 98 and store
it in the file 'example.jpg'

Ming Jiang www.wcomms.com 26


Exporting a Plot as a Graphical Image (2/2)

• The "File/Save As"


menu option on
the Figure
Window can be
used to save a
plot as a
graphical image

Ming Jiang www.wcomms.com 27


Multiple Plots (1/2)

• It is possible to plot multiple functions


on the same graph
• Simply include more than one set
of (x, y) values in the plot function

Quiz: Plot the two functions f(x), g(x) on the


same figure

 f ( x)  sin(2 x)

 d  f ( x) 
 g ( x)  dx  2 cos(2 x)

Ming Jiang www.wcomms.com 28


Multiple Plots (2/2)

x = 0:pi/100:2*pi;
y1 = sin(2*x);
y2 = 2*cos(2*x);
plot(x,y1,x,y2);

% Incorrect
>> plot(x,y1,y2)
>> plot(x,y1;x,y2)

Ming Jiang www.wcomms.com 29


Line Color, Line Style, Marker Style (1/2)

Ming Jiang www.wcomms.com 30


Line Color, Line Style, Marker Style (2/2)
Example --: dashed o: circle

x = 0:1:10; r: red b: blue


y = x.^2 - 10.*x + 15;
plot(x,y); plot(x,y,'r--',x,y,'bo');

Ming Jiang www.wcomms.com 31


Legends (1/4)

• Create with the legend function


legend('string1', 'string2',..., pos)
•string1, string2, … : the labels associated with
the lines plotted
•pos: a string specifying where to place the legend

Ming Jiang www.wcomms.com 32


Legends (2/4)

legend('string1', 'string2',..., pos)


Specifier Location in Axes
North Inside plot box near top
South Inside bottom
East Inside right
West Inside left
NorthEast Inside top right (default for 2-D plots)
Specifiers
NorthWest Inside top left defined in
SouthEast Inside bottom right MATLAB 2013b
SouthWest Inside bottom left
NorthOutside Outside plot box near top
and later
SouthOutside Outside bottom versions
EastOutside Outside right
WestOutside Outside left
NorthEastOutside Outside top right (default for 3-D plots)
NorthWestOutside Outside top left
SouthEastOutside Outside bottom right Check help by
SouthWestOutside Outside bottom left
Best Least conflict with data in plot
yourself!
BestOutside Least unused space outside plot

Ming Jiang www.wcomms.com 33


Legends (3/4)

Example  f ( x)  sin(2 x)

 d  f ( x) 
 g ( x)  dx  2 cos(2 x)

x = 0:pi/100:2*pi;
y1 = sin(2*x);
y2 = 2*cos(2*x);
plot(x,y1,'k-',x,y2,'b--');
title('Plot of f(x) and g(x)');
xlabel('x');
ylabel('y');
legend('f(x)','g(x)','location','NorthWestOutside');
grid on;

Ming Jiang www.wcomms.com 34


Legends (4/4)

legend('f(x)','g(x)','location','NorthWestOutside');

legend('f(x)','g(x)','location','Best');
Least conflict
with data in plot

Ming Jiang www.wcomms.com 35


Logarithmic Scales (1/3)

Four possible combinations of linear and


logarithmic scales on the x and y axes
•plot x = y = linear
•semilogx x = logarithmic, y = linear
•semilogy x = linear, y = logarithmic
•loglog x = y = logarithmic

Ming Jiang www.wcomms.com 36


Logarithmic Scales (2/3) Example x = 0:1:10;
y = x.^2 - 10.*x + 30;

plot semilogx

semilogy loglog
Logarithmic Scales (3/3)

Example
SNR: Signal-to-Noise Ratio
Logarithmic
SNR = [0 2 4 6 8 10]; scale is useful
BER = [0.1 3e-2 6e-3 5e-4 2e-5 6e-7];
for expanding
BER = Bit Error Rate small data
ranges

plot semilogy

Ming Jiang www.wcomms.com 38


Engineering Example (1/3)

• Prerequisites:
• Voltage source: V = 120 V Example:
• Internal resistance: RS = 50 ohms
Power Circuits
• Load of resistance: RL
• Questions:
• Plot the power supplied to the load as a
function of RL
• Find the max power PLmax supplied to the load

 V V
I  R 
RS  RL
 TOT
P  I 2 R
 L L

V 2 RL
PL  I RL 
2

( RS  RL ) 2

Given V=120 and RS=50, to maximize PL: PL,max=?


Engineering Example (2/3)

% Define variables:
% PL -- Power supplied to load (watts) M-file
% RL -- Resistance of the load (ohms)
% RS -- Internal resistance of the power source (ohms)
% V -- Voltage of the power source (volts)

% Set the values of source voltage and internal resistance


V = 120;
RS = 50;
% Create an array of load resistances
RL = 1:1:100;

% Calculate the power supplied to the load


PL = ( V^2 * RL ) ./ ( RS + RL ) .^ 2;

% Plot the power versus load resistance


plot(RL,PL);
title('Plot of power versus load resistance');
xlabel('Load resistance (ohms)');
ylabel('Power (watts)');
grid on;

Ming Jiang www.wcomms.com 40


Engineering Example (3/3)

Solution:
RL = 50 ohms
PL,max = 72 V

Ming Jiang www.wcomms.com 41


MATLAB Programming for Engineers
Chapter 2: MATLAB Basics (Part 2)

• Scalar and Array Operations


• Hierarchy of operations
• Built-in MATLAB functions
• Basics of plotting
• Debugging MATLAB

Ming Jiang
Debugging MATLAB Programs (1/2)

There are only 3 SURE things in the world:

• Heaven • Taxes

• Long programs will NOT work


the first time you try it!

Ming Jiang www.wcomms.com 43


Debugging MATLAB Programs (2/2)

Three types of errors


• Syntax errors
• Spelling errors
• Punctuation errors
• Run-time errors
• An illegal mathematical operation is attempted
during program execution
• e.g. attempting to divide by 0
• Logical errors
• The program compiles and runs successfully, but
produces the wrong answer

Ming Jiang www.wcomms.com 44


Debugging Methods (1/2)

Check the initialization of variables


• Whether their names are the same as built-in functions
• Ensure all variables are initialized properly
• Ensure use of correct units for the values of variables
• e.g. the input to trigonometric functions must be in
units of radians, not degrees

Check statements
• Check the placement of parentheses
• Break long assignment statement into smaller ones

Check functions
• Ensure input/output data of functions are correct

Ming Jiang www.wcomms.com 45


Debugging Methods (2/2)

Check run-time values of


variables
• Remove semicolons from
input statements, or add
extra output statements
• Use MATLAB's built-in step-
by-step debugger for M-files
•Set Break Points
•Debugging operations:
Step In/Step Out/Run to
Cursor/Continue

Ming Jiang www.wcomms.com 46


版权说明

■ 本课程的课件
● 主要内容:本人制作
● 部分内容:参考了中山大学数据科学与计算机学院张雨浓教授
的2008年版课件
● 少量内容:参考了Kasetsart University的James Brucker博士
早期的课件
■ 下载地址:
http://www.wcomms.com/lectures/course-matlab.html

本课件及相关作业,仅限本课程教学使用
请勿上传互联网
谢谢合作!
WWW.WCOMMS.COM

You might also like