Вы находитесь на странице: 1из 129

MATLAB PROGRAMMING

An Engineering Perspective

Mr. Ankush Vashistha


Mr. Lu Kunze
School of EEE
Email: ies@e.ntu.edu.sg
Outline
Introduction
MATLAB Fundamental
Basic Graphics
MATLAB Programming
Applications in Engineering Contexts
Introduction

MAT-LAB
{Matrix - Laboratory}
Uses of MATLAB
Computational tool widely used in science and engineering
encompassing the fields of physics, chemistry, math and all
engineering streams.
Signal processing and communications
Image and Video Processing
Control System
Signal Processing

How this signal (Sine


Wave) looks like in a
Matrix Form ?
Image and Video Processing
Image and Video Processing Example
Starting MATLAB, MATLAB Windows
Window Purpose
Command Window Main window, enters variables, runs programs
Figure Window Contains output from graphic commands
Editor Window Creates and debugs scripts and function files
Help Window Provides help information
Workspace Window Provides information about the variables that are used
Command History Window Logs commands entered in the Command Window
Current Folder Window Shows the files in the current folder
MATLAB Windows

Workspace
Command Window Displays any
MATLAB commands variables created
Current Folder Window are entered here.
Shows the files in the current folder.

Command History
Lists all commands previously entered
.
If you want to see help,
you can type help at the
command window

If you want to see help,


you can type help at the
command window.
You can also press F1 to
display the help window.
Click on Open Help Browser
to search for a specific
function.
Example: search for
function mean
MATLAB Fundamentals
MATLAB as a calculator
Elementary math built-in functions
Assignment operator
Script files
Creating vectors and matrices
Matrix manipulation
Element-by-element calculation
MATLAB as a calculator
>> 7+8/2 Type and press Enter
ans =
8/2 executed first
11
>> (7+8)/2 Type and press Enter
ans = 7+8 executed first
7.5000
>> 4+5/3+2 5/3 executed first
ans =
7.6667
1/3 first, 27^(1/3) and 32^0.2 are
>> 27^(1/3) + 32^0.2
executed next
ans =
5
Elementary Math Built-in Functions
Function Description Example

sqrt(x) Square root >> sqrt(50+14*3)


ans =
9.5917
exp(x) Exponential (e^x)
abs(x) Absolute value
log(x) Base e logarithm (ln) >> log(1000)
ans =
6.9078
factorial(x) x! (x must be
positive)
sin(x) Sine in radians >> sin(pi/6)
ans =
0.5000
cos(x) Cosine in radians
tan(x) Tangent in radians
cot(x) Cotangent in radians
Declaring single variables
To declare single variables, type in a variable name and
type in its value.

Example:
var1 = 3;
var2 = 56.7;
Cont.
Cont..
>> a=15 Number 15 is assigned to a
a=
15 MATLAB displays value of assigned value
>> a=a-3 New value is assigned to a
a=
12
>> B=4 Assign 4 to B
B=
4
>>C=(a-B)+40-a/B*10 Assign the value of expression to C
C=
18
Illegal variable name
Variables cannot have numbers or symbols in front of them.

Examples of illegal variable name:

1var=1
#var=45
Extra comments
MATLAB is case-sensitive
When semicolon is pressed at the end of the command, we can stop
MATLAB from displaying the variable with assigned value.
>> a=15;
>> a=a-3; The variables a and B are not
displayed, since semicolon is
>> B=4;
pressed.
>>C=(a-B)+40-a/B*10
C=
18
Useful commands
Command Outcome
who Display a list of variables currently in the memory
whos Display a list of variables together with their bytes and class
clear x, y, z Remove only variables x, y and z
clear Remove all variables from the memory
clc Clear the command window without removing the variables
close all Close all windows
Who example
Whos Example
Clear var1, var2
Clear
Quick example
1. Create a variable x and assign a value of 6 to it
2. Find the value of x!
3. Find the value of ln(x)
4. Create a variable y and assign a value of 3 to it
5. Find x+y
6. Subtract 2 from x and assign the new value in x.
7. Find x to the power of y
8. Display all variables in the memory
9. Clear all variables
10.Clear the command window
Script Files
A script file is a sequence of MATLAB commands, also called a
program
When a script file runs, MATLAB executes the commands in the order
they are written just as if they were typed in the Command Window
When a script file has a command that generates an output, the
output is displayed in the Command Window
Convenient because it can be edited (corrected or other- wise
changed) and executed many times
Also called M-files because of the extension .m
To open a new script file.
Press New.
Saving a Matlab Script File
To execute a program, press
the RUN button.
Example 1
The current I (in amps) t seconds after closing the switch in the circuit
shown is :

Given V = 120V, R = 240ohms, L = 0.5henrys, calculate the current


0.003 sec and 0.300 sec after the switch is closed.
Example 1 Solution (using script file)
V=120;R=240;L=0.5; Defining variables

t=0.003;
I=V/R*(1-exp((-R/L)*t))
When no semicolon is pressed,
results will be displayed.
t=0.300;
I=V/R*(1-exp((-R/L)*t))
Creating vectors and matrices
>> [1 2 3 4]
ans =
Create a row vector, comma can be
1 2 3 4 omitted
>> [1,2,3,4]
ans =
1 2 3 4
>> [1 2; 3, 4] Create a matrix; use semicolon to
ans = start a new row
1 2
3 4
Creating vectors and matrices
>> year = [2010 2012 2014 2016] Assign a list of numbers to row
year = vector year
2010 2012 2014 2016
>> year = 2010:2:2016 m:q:n, where m is the first element,
year = q is the interval and n is the last
2010 2012 2014 2016 element (q can be +ve or -ve)
>> y=1:5 If interval is 1, it can be omitted
y=
1 2 3 4 5 linspace(xi,xf,n), where xi is first
>>x=linspace(0, 6, 4) element, xf is last element, n is the
x= number of elements
0 2 4 6
>>disp(year) A good practice to display the matrix
2010 2012 2014 2016 using command disp(matrixName)
Accessing elements
Specific elements in the matrix can be accessed
Syntax:
matrixName(rowNumber, colNumber)
Example: to access a value inside mat3
mat3=[1 2 3 4; 5 6 7 8; 6 7 8 9];
disp(mat3) 1 2 3 4
var11=mat3(1,1)
var23=mat3(2,3) 5 6 7 8
What if the following is executed? 6 7 8 9
var1=mat3([1 2], [2 3])
var2=mat3(:, 2)
var3=mat3(1:2:3,:)
Cont.....
Matrix manipulation
>> W=[1 2; 3 4] + 5 Matrix expansion
W=
6 7
8 9

>> A=[W, W*2; W*3, W*4]


A= Matrix concatenation
6 7 12 14
8 9 16 18
18 21 24 28
24 27 32 36
Matrix manipulation
>> W=[1 2; 3 4] * 2
W=
2 4
6 8
>> A=exp(W/2)
A=
2.7183 7.3891
20.0855 54.5982
>> A=[1 2 3; 4 5 6]; B=[3,1;2,4;-1,2]; C=A*B
C=
4 15
16 36
Element-by-Element Operations
>> A=[2 6 3; 5 8 4];B=[1 4 10; 3 2 7];
>>A.*B Element-by-element
multiplication
Ans =
2 24 30
15 16 28
>> C=A./B
Element-by-element
C=
division
2.0000 1.5000 0.3000
1.6667 4.0000 0.5714
>> B.^3 Element-by-element
Ans = exponentiation of
1 64 1000 array B. What happens
if we omit the dot?
27 8 343
More examples
>> z=1:2:7 Create a vector z with
z= 5 elements
1 3 5 7
>>Y=(z.^3+5*z)./(4*z.^2-10) Vector z is used in
element-by-element
Y= calculations of the
-1.0000 1.6154 1.6667 2.0323 elements of vector Y
>> Y=cos([0:(pi/3):pi])
Y=
1.0000 0.5000 -0.5000 -1.0000
Some useful functions
Function Description Example
mean(A) Returns mean value of all elements in vector A >> A=[5 2 9 4]; mean(A)
Ans =
5
max(A) Returns maximum value in vector A
min(A) Returns minimum value in vector A
sum(A) Returns sum of all elements in vector A
det(A) Returns determinant of square matrix A
cross(A,B) Returns cross product of two vectors A and B >> A=[1 3 2];B=[2 4 1];
cross(A,B)
Ans =
-5 3 -2
dot(A,B) Returns dot product of two vectors A and B

* For the first four functions, what if A is a matrix?


An example on matrix manipulation
Given the array A = [2 7 9 7 ; 3 1 5 6 ; 8 1 2 5], B=[1:4;1:2:7;4:-1:1] explain
the results of the following commands:
1. A(1,2)
2. A([2 3],[3 1])
3. sum(A)
4. max(max(A))
5. A-B.^2
6. log(A*3)
7. log(A.*B)
8. sin(B-2)
Example 2 (using script file)
The coefficient of friction can be determined by experiment through
the formula

Results from a set of 6 experiments are shown in the table below

Mass m(kg) 2 4 5 10 20 50

Force (F(N)) 12.5 23.5 30 61 117 294

Determine the coefficient of friction in each test, and find the mean.
Solution
mass=[2 4 5 10 20 50];
force=[12.5 23.5 30 61 117 294];
g=9.81;
miu=force./(mass*g);
disp(miu);
disp(mean(miu));
Basic Graphics
The plot command
Two-dimensional plots
Subplots
Applications in Engineering
The plot command Line Specifier

Syntax (x and y are vectors) solid (default) -


dashed --
plot(x,y)
dotted :
plot(x, y, line specifiers) red r
green g
Eg. blue b
plot(x,y) blue solid line (default) yellow y
black k
plot(x,y,r) red solid line
square s
plot(x,y,--y) yellow dashed line
diamond d
plot(x,y,g:d) green dotted line with diamond markers asterisk *
cross x
plus +
point .
The plot command (B=3sinA)
Create vector A with domain of function
A=linspace(-2*pi,2*pi,1000);
B=3*sin(A); Create vector B with the
function value at each A
plot(A,B); 3

Plot B as function of A 2

-1

-2

-3
-8 -6 -4 -2 0 2 4 6 8
The plot command ( y=2 -0.5x cos(6x) )
Create vector X with
X=-6:0.01:6; domain of function
Y=2.^(-0.5*X).*cos(6*X); Create vector y with the
function value at each X
plot(X,Y); Plot Y as function of X 8

-2

-4

-6

-8
-6 -4 -2 0 2 4 6
Two-dimensional plots
Function Description
plot(x, y, -b, a, b --r) Y vs x with solid blue line, b vs a with dashed red line on the
same graph
figure Create a new figure
axis([xmin,xmax,ymin,ymax]) Set limit for both x and y in the graph
title(name of plot) Insert title of the current plot
legend(xxx, xxx, ) Insert legend(s) of the plot
xlabel(name of variable x) Insert name of horizontal axis
ylabel(name of variable y) Insert name of vertical axis
semilogy(x,y) Plot y vs x with a log (base 10) scale for y axis only
semilogx(x,y) Plot y vs x with a log (base 10) scale for x axis only
loglog(x,y) Plot y vs x with a log (base 10) for both axis
Quick Example
A=linspace(-2*pi,2*pi,1000);
B=3*sin(A);
plot(A,B); 10
sine wave

sin(x)

axis([-2*pi,2*pi,-10,10]); 8

title(sine wave); 4

legend(sin(x));
2

y
xlabel(x); -2

-4

ylabel(y); -6

-8

-10
-6 -4 -2 0 2 4 6
x
Two-dimensional plots

How do we plot two graphs in the same figure?

Function Description
plot(x, y, -b, a, b --r) Y vs x with solid blue line, b vs a with dashed red line on the same graph
grid on Create a grid on the current figure
grid off Turn off the grid from current figure
hold on Hold the current plot
hold off Release hold on current plot
Quick Example 8 10
3
y=3sin(x)

A=linspace(-2*pi,2*pi,1000); 8 y=2 (-0.5x)*cos(6x)


6

2
6

B=3*sin(A);
4
4
1
2

plot(A,B,b);
2

0 0

y
hold on; -2
-2

-1

X=-6:0.01:6;
-4
-4
-6
-2

Y=2.^(-0.5*X).*cos(6*X); -6
-8

-3

plot(X,Y,r);
-8-10 -8 -6 -4 -2 0 2 4 6 8
-8 -8 -6 -6 -4-4 -2-2 00 22 44 66 88
x

axis([-8,8,-10,10]);
legend(y=3sin(x),y=2^(-0.5x)*cos(6x));
xlabel(x);
ylabel(y);
Different types of plots (Refer to Appendix)

Bar Plot Bar Plot Pie Plot

Area Plot
Stem Plot Scatter Plot
Example 3
x=linspace(-2*pi,2*pi,1000);

sinx=sin(x);
oneterm=x;
twoterm=x-x.^3/factorial(3);
fiveterm=x-x.^3/factorial(3)+x.^5/factorial(5)-x.^7/factorial(7)+x.^9/factorial(9);

plot(x, sinx);
hold on;
1
40
2

0.8 sin(x)
one term

plot(x, oneterm, :k); plot(x, twoterm, --r); plot(x, fiveterm, *g);


30
1.5 two terms
0.6 five terms

20

legend (sin(x), one term, two terms, five terms); 0.41

0.2
10

xlabel(x); ylabel(sin(x)); 0.5

00

sin(x)
axis([-8 8 -2 2]); 0
-0.2
-10

-0.4
-0.5
-20

-0.6
-1
-30
-0.8

-1.5
-40
-1 -8 -6 -4 -2 0 2 4 6 8
-8 -6 -4 -2 0 2 4 6 8

-2
-8 -6 -4 -2 0 2 4 6 8
x
Subplot Example:
A=linspace(-2*pi,2*pi,1000);
B1=3*sin(A); Subplot(m,n,p), where
B2=3*cos(A); m is no. of rows, n is no.
X=[-6:0.01:6]; of columns, p is the
Y1=2.^(-0.5*X).*cos(6*X); position of the plot.
Y2=2.^(-0.5*X).*sin(6*X);
subplot(2,2,1); 3 3
3 33

plot(A,B1);
3
2 3 2
2 2 22
2
1 1 1
11
1

subplot(2,2,2); 0
0
-1 -1
-1
0
1

0
0

-1
0

-1
-1

plot(A,B2); -2 -2
-2
-3
-2
-3
-10
-3-10 -3 -5 0 5 10
-2
-2
-2
-3
-3-10
-3 -5 0 5 10
-5 -5 0 0 5 5 10 -10 -5 0 5 10

subplot(2,2,3);
-10 -10 -5 0 5 10
10 -10 -5 0 5 10

10
10 10

plot(X,Y1); 5
5

0
5

subplot(2,2,4); 0
-5
0

-5 -5

plot(X,Y2); -10
-10
-10
-10

-5
-5

0
0

5
5 10

10
-10
-10 -5 0 5 10
Example 4
t=linspace(0,8,1000);
position=0.41*t.^4-10.8*t.^3+64*t.^2-8.2*t+4.4;
velocity=1.64*t.^3-32.4*t.^2+128*t-8.2;
acceleration=4.92*t.^2-64.8*t+128; 600

400

x(t)/ft
200
subplot(3,1,1); 0

plot(t, position); 0 1 2 3 4
t/s
5 6 7 8

200
xlabel(t/s); ylabel(x(t)/ft);

v(t)/ft*s- 1
0

subplot(3,1,2); -200

plot(t, velocity); -400


0 1 2 3 4 5 6 7 8

xlabel(t/s); ylabel(v(t)/ft*s^-1); 200


t/s

subplot(3,1,3);

a(t)/ft*s- 2
100

plot(t, acceleration); 0

-100
xlabel(t/s); ylabel(a(t)/ft*s^-2); 0 1 2 3 4
t/s
5 6 7 8
Practice yourself (for AERO)
Practice yourself (for CBE)
Practice yourself (for EEE)
Practice yourself (for ME)
Practice yourself (for CE)
MATLAB Programming
Relational operators
Conditional statements
Loops
User-defined functions
Relational operators
Operator Description
< Smaller than
> Greater than
<= Smaller than or equal to
>= Greater than or equal to
== Equal to (different from =)
~= Not equal to
& and
| or
~ not
Relational operators
>> A=5<10 Check if 5 is less than 10, then assign the value to A
A=
1
>> Y=(6<10)+(7>8)+(5*3==60/4) Use relational operations in math expressions
Y=
2
>> B=[15 6 9]; C=[8 20 9];
>> D=C>=B Check which C elements is not less than B elements
D=
0 1 1
>> B~=C Check which B elements are not equal to C elements
Ans =
1 1 0
Relational operators
>> x=[9 3 0 11]; y=[2 0 13 -11];
>> x&y 1 if both elements are true (non-zero)
ans =
1 0 0 1
>> ~(x+y)
ans =
0 0 0 1
>> r = [8 12 9 4];
>> s=r<10 Check which r elements are smaller than or equal to 10
s=
1 0 1 1
>> t=r(s) Use s for addresses in vector r to create t
t=
8 9 4
Some useful functions
Function Description Example
disp(string) Display a string disp(MATLAB is easy);
fprintf(string) Similar to printf function in C fprintf(Answer is %f\n, value);
input(string) Display a string prompting the
user to enter a value that is to
be assign to the variable
Conditional statement
Syntax: Example:
if ... >> mark=input(Please enter the mark: );
... if mark>=80
elseif ... disp(Grade: Distinction);
...... elseif mark>=60
else disp(Grade: Pass);
...... else
end disp(Grade: Fail);
end
Loops
For loops While loops

for k=f:s:t while ...


... ......
...... ......
end end
Example 5
Create a matrix such that the elements in the first row equal to the
number of column and first column equal to the number of row, and
every other element is equal to the sum of element above it and the
element to the left.
The program asks the user to input the number of rows and columns
of the matrix.
1 2 3 4
2 4 7 11
3 7 14
4 11
...
n=input(Number of rows: );
m=input(Number of columns:);
A=[];
for i=1:n
for j=1:m
if i==1
A(i,j)=j;
elseif j==1
A(i,j)=i;
else
A(i,j)=A(i-1,j)+A(i,j-1);
end
end
end
A
Quick Review
Create a matrix such that each element has a value equal to the sum
of the row & column the element is at.
The program asks the user to input the number of rows and columns
of the matrix.

2 3 4 5
3 4 5 6
4 5 6
5 6
...
User-defined functions
Example 6
Write a function that has input of three lengths and outputs a string
denoting if a triangle can or cannot be formed from the lengths
provided.
Noted: A triangle can only be formed if the sum of any two sides is
greater than that of the third.
Solution
Practice yourself
Practice yourself
References
Amos Gilat, MATLAB An Introduction with Applications, Fourth
Edition, Department of Mechanical Engineering, The Ohio State
University, JOHN WILEY & SONS, INC., November 2016.
Appendi
x
Different types of plots in MATLAB
Bar plot
Types of bar plot:

Example-
Y = [5,2,1 8,7,3 9,8,6 5,5,5 4,3,2];
bar(Y, grouped);

MATLAB
Contd.

Distribute the bars


along x axes

MATLAB
Contd.
To stack the elements in a row, specify the stacked
option for the bar function.
>>bar(Y,'stacked');

Stacked the elements


in a row

MATLAB
Contd.
To distributes bars along the y-axis.
>>barh(Y);

Distribute the bars


along y axes

MATLAB
Contd.
To draws each element as a separate 3-D block and
distributes the elements of each column along the y-axis.
>>bar3(Y);

MATLAB
Contd.
To stack the elements in a row, specify the stacked
option for the bar3 function.
>>bar3(Y,'stacked');

MATLAB
Contd.
To draws each element as a separate 3-D block and
distributes the elements of each column along the z-axis.
>>bar3h(Y);

MATLAB
Pie graph
pie(X) draws a pie chart using the data in X. Each
element in
X is represented as a slice in the pie
chart.
If sum(X) 1, then the values in X directly specify
the area of the pie slices. pie draws only a partial
pie if sum(X) < 1.
If the sum of the elements in X is greater than one,
then pie normalizes the values by X/sum(X) to
determine the area of each slice of the pie.
Example-
x = [1,3,0.5,2.5,2];
pie(x);
MATLAB
Contd.

MATLAB
Contd.
To offset the second and fourth pie slices, set the
corresponding explode elements to 1.
Example- explode = [0,1,0,1,0];
pie(x,explode);

Second pie slice Fourth pie slice

MATLAB
Contd.
To specify the text labels for a pie chart.
Example- x = 1:3;
labels ={'Taxes','Expenses','Profit'};
pie(x,labels);

94
MATLAB
Contd.

To create a partial pie chart.


Example-
x = [0.19,0.22,0.41];
pie(x);

Since the sum of the elements in x is less than 1, pie draws a


partial pie.

MATLAB
Contd.
Fourth pie slice
is not present

MATLAB
Pie3
It draws a three-dimensional pie chart using the
data in X.
Each element in X is represented as a slice in the pie
chart.
If sum(X) 1, then the values in X directly specify
the area of the pie slices. pie3 draws only a partial
pie if sum(X) < 1.
If the sum of the elements in X is greater than one,
then pie normalizes the values by X/sum(X) to
determine the area of each slice of the pie.
Example-
x = [1,3,0.5,2.5,2];
pie3(x);
MATLAB
Contd.

MATLAB
Contd.
To offset the second pie slice, set the corresponding explode
element to 1.
Example- explode = [0,1,0,0,0];
pie3(x,explode);

MATLAB
Area graph
An area graph displays elements in Y as one or more
curves and fills the area beneath each curve. When Y is a
matrix, the curves are stacked showing the relative
contribution of each row element to the total height of
the curve at each x interval.
area(Y) plots the vector Y or plots each column in matrix
Y as a separate curve and stacks the curves. The x-axis
automatically scales to 1:size(Y,1).
area(X,Y) For vectors X and Y, area(X,Y) is the same as
plot(X,Y) except that the area between 0 and Y is filled.
When Y is a matrix, area(X,Y) plots the columns of Y as
filled areas. For each X, the net result is the sum of
corresponding values from the rows of Y.

MATLAB
Example
Plot the data in matrix Y as an area graph.
Example- Y = [1, 5, 3; 3, 2, 7; 1, 5, 3; 2, 6, 1];
area(Y);
Stacked the second
Column with the
first column.

Plot the first


column of y matrix

MATLAB
Example
By default, area uses the y-axis as the base value. Change the
base value by setting the basevalue input argument to -4.
Y = [1, 5, 3; 3, 2, 7; 1, 5, 3; 2, 6, 1];
basevalue = -4;
area(Y,basevalue);

MATLAB
Contd.

Base value set


to -4

MATLAB
Stem plot
stem(Y) plots the data sequence, Y, as stems that extend
from a baseline along the x-axis. The data values are
indicated by circles terminating each stem.
stem(X,Y) plots the data sequence, Y, at values specified by X.
The X and Y inputs must be vectors or matrices of the same
size. Additionally, X can be a row or column vector and Y
must be a matrix with length(X) rows.

MATLAB
Example
Create a stem plot of 50 data values between -
2*pi and 2*pi. Y = linspace(-2*pi,2*pi,50);
stem(Y);

MATLAB
Example
Plot two data series using a two-column matrix.
X = linspace(0,2*pi,50)';
Y = [cos(X), 0.5*sin(X)]; Sine plot
stem(Y);

Cos plot

MATLAB 81
Example
Plot 50 data values of cosine evaluated between 0 and specify the
set of x values for the stem plot.
X = linspace(0,2*pi,50)';
Y = cos(X);
stem(X,Y);

MATLAB 82
Example
Plot 50 data values of sine and cosine evaluated between
0 and specify the set of x values for the stem plot.
X = linspace(0,2*pi,50)';
Y = [cos(X), 0.5*sin(X)];
Sine plot
stem(X,Y);

Cos plot

MATLAB 83
Example
Plot 50 data values of sine and cosine evaluated at different
sets of x values. Specify the corresponding sets of x values
for each series.
x1 = linspace(0,2*pi,50)';
x2 = linspace(pi,3*pi,50)';
X = [x1, x2];
Y = [cos(x1), 0.5*sin(x2)];
stem(X,Y);

MATLAB
Contd.

Cos and sine plot


with different
x values

MATLAB
Example
Create a stem plot and fill in the circles that terminate
X = linspace(0,10,20)';
Y = (exp(0.25*X));
stem(X,Y,'fill');

MATLAB 86
Example
Create a figure with two subplots and return the handles to
each axes, s(1) and s(2). Create a stem plot in the lower
subplot by referring to its axes handle, s(2).
s(1) = subplot(2,1,1);
s(2) = subplot(2,1,2);
X = 0:25;
Y = [exp(0.1*X); -exp(.05*X)]';
stem(s(2),X,Y);

MATLAB
Contd.
S(1) subplot

S(2) subplot

MATLAB
Scatter plot
Scatter(X,Y) displays circles at the locations specified by the
vectors X and Y. This type of graph is also known as a bubble
plot.
Scatter(X,Y,S) draws each circle with the size specified by S.
To plot each circle with equal size, specify S as a scalar. To
plot each circle with a specific size, specify S as a vector
with length equal to the length of X and Y.
Scatter(X,Y,S,C) draws each circle with the color specified by
C.

MATLAB
Example
Define x to contain 200 equally spaced values between 0
and . Initialize the random-number generator to make
the output of rand repeatable, and define y to contain
cosine values with random noise.
x = linspace(0,3*pi,200);
y = cos(x)+ rand(1,200);
scatter(x,y);

MATLAB 90
Example
Vary circle size and color.
s = linspace(1,50,length(x));
Large size circles
c = linspace(1,10,length(x));
scatter(x,y,s,c);
zoom(2);

Small size circles

MATLAB 91
Example
To fill the circles.
scatter(x,y,s,c,'fill');

Large size filled circles

Small size
filled circles

MATLAB
Example
Create a figure with two subplots and return the handles to
the two subplot axes in array hs. Create a scatter plot in the
upper subplot using the axes handle, hs(1). In the lower
subplot, create another scatter plot from the same data
sample and use filled, diamond markers.
hs(1) = subplot(1,2,1);
hs(2) = subplot(1,2,2);
s = 30;
c = linspace(1,10,length(x));
scatter(hs(1),x,y,s,c);
scatter(hs(2),x,y,s,c,'fill','d');
MATLAB
Example
Subplot 2
Subplot 1

Diamond
Circle marker marker

MATLAB
Scatter3
Scatter3(X,Y,Z) displays circles at the locations
specified by
the vectors X, Y, and Z.
Scatter3(X,Y,Z,S) draws each circle with the size
specified by
S. To plot each circle with equal size, specify S as a
scalar. To
plot each circle with a specific size, specify S as a
vector.
Scatter3(X,Y,Z,S,C) draws each circle with the color
specified by C.
MATLAB
Example
Create a 3-D scatter plot. Use sphere to define vectors x, y,
and z.

[X,Y,Z] = sphere(16);
x = [0.5*X(:); 0.75*X(:); X(:)];
y = [0.5*Y(:); 0.75*Y(:); Y(:)];
z = [0.5*Z(:); 0.75*Z(:); Z(:)];
scatter3(x,y,z);

MATLAB
Contd.

Z-axis

Y-axis X-axis
MATLAB
Example
Vary marker size, marker color and fill the marker.

S = repmat([50,25,10],numel(X),1);
C = repmat([1,2,3],numel(X),1);
s = S(:);
c = C(:);
scatter3(x,y,z,s,c, 'fill');

MATLAB
Contd.

Large size filled circles


Small size filled circles

MATLAB
Hint for AERO Practice Question
Create a row vector x whose first element is 0 and last element is 1.5
Create vector y with the function value at each x.
Plot y against x
Hint for CBE Practice Question
Create a row vector t whose first element is 0 and last element is 10.
Create vector Cp with the function value at each t.
Plot Cp against t.
Hint for EEE Practice Question
Create a row vector R1 whose first element is 0 and last element is
500.
Create vector Vab with the function value at each R1.
Plot Vab against R1, using subplot(2,1,1)
Repeat the same for R2, using subplot(2,1,2)
Hint for ME Practice Question
Create a row vector t whose first element is 0 and last element is 10.
Create vector x with the function value at each t.
Plot x against t.
Hint for CE Practice Question
Create a row vector x whose first element is 0 and last element is 10.
Create vector y with the function value at each x.
Plot y against x.
Hold on the graph.
Repeat the steps using x as a row vector which starts from 10 and
ends at 20.

Вам также может понравиться