You are on page 1of 35

Introduction to Programming

with MATLAB

Lecture#8&9:
Working with datasets(Data
visualization and Plotting)
DR. Eman Abdulazeem Ahmed
Import & Export of Data

❑ Most of your data starts off outside


matlab…you need to get it imported.
❑ Simple ascii files:
> load file.txt –ascii

MATLAB Differential and


Integral MATLAB Differential
and Integral Calculus, Cesar
DR. Eman Abdulazeem Ahmed
Lopez, Cesar Lopez 2
Import Wizard
❑ The Import Wizard is a feature in MATLAB that
determines the type of data file and determines the
way to extract and display the information within
MATLAB.
❑ It can be used to extract data from ASCII files, Excel
spreadsheet files, among others.
❑ Import Wizard is opened by double clicking on a file
MATLAB
name in theDifferential and
current directory window of the desktop.
Integral MATLAB
❑ If abc.xlsx Differential
have the coloumn
and Integral Calculus, Cesar
❑ A=importdata(‘abc.xlsx’) abc.xlsx
Lopez, Cesar Lopez
DR. Eman Abdulazeem Ahmed 3
uiimport Function
❑ Another way to open the Import Wizard is to
type uiimport('filename.extension') in the
command window.
❑ The single quotes around the name of the file
are very important; the wizard will not run if
they are omitted.
MATLAB Differential and
Integral MATLAB Differential
and Integral Calculus, Cesar
DR. Eman Abdulazeem Ahmed
Lopez, Cesar Lopez 4
Importing an Excel data file

xlsread('filename.xls')
❑ Before you can use this command you need to
ensure that where ever the file is stored is in
your path. (File → Set path)
❑ Note that if Excel is not installed on the
computerDifferential
MATLAB MATLAB cannot and use xlsread or
xlswrite.
Integral MATLAB Differential
and Integral Calculus, Cesar
DR. Eman Abdulazeem Ahmed
Lopez, Cesar Lopez 5
textread Function
❑ textread allows MATLAB to read ASCII files.
❑ The file must be formatted into columns, but each
column can be a different data type. The construct is:
[a,b,c,d…] = textread(‘filename’,
‘%f %d %d %d…’, n),
❑ a,b,c,d… represent the names of each variable,
❑ filename is the name of the file,
❑ ‘%f %d %d %d…’ is a string indicating the format
MATLAB Differential and
of the variables in the text file,
Integral MATLAB
❑ n is number of rows toDifferential
be read. If n is not included in
andtheIntegral
command,Calculus, Cesar
the entire file is read.
DR. Eman Abdulazeem Ahmed
Lopez, Cesar Lopez 6
GRAPHICS
GRAPHICS

❑ Basic Plotting
❑ Linetypes, markers, colours, etc
❑ Subplots – creating multiple axes on a
single figure
❑ Annotating figures – titles, labels, legends
MATLAB
❑ Editing Differential and
figure properties
Integral
❑ OtherMATLAB Differential
plotting functions
and Integral Calculus, Cesar
DR. Eman Abdulazeem Ahmed
Lopez, Cesar Lopez 8
Basic 2D Plotting Commands
❑ figure : creates a new figure window

❑ plot(x) : plots line graph of x vs index


number of array

❑ plot(x,y) : plots line graph of x vs y


❑ plot(x,y,'r--') : plots x vs y with linetype
MATLAB Differential and
specified in string.
Integral
'r' = red, MATLAB Differential
'g'=green, etc
and Integral Calculus,
'−' solid line, Cesar
for a limited set of '− −' dashed, DR. Eman Abdulazeem Ahmed
Lopez,
basic Cesar Lopez
colours. 'o' circles 9
Nomenclature for a typical xy plot.

MATLAB Differential and


Integral MATLAB Differential
More? See
and Integral Calculus, Cesar pages 260-
Lopez,
DR. Cesar Lopez
Eman Abdulazeem Ahmed 261.10
Rocket Example
The following MATLAB session plots
y = 0.4 1.8x for 0  x  52,
where
y represents the height of a rocket after launch, in miles,
x is the horizontal (downrange) distance in miles.
x = [0:0.1:52];
y = 0.4*sqrt(1.8*x);
plot(x,y)
xlabel('Distance (miles)')
ylabel('Height (miles)')
MATLAB Differential
title('Rocket and as a Function of
Height
Downrange Distance')
Integral MATLAB Differential
andTheIntegral
resulting plot is shown on the next slide.
Calculus, Cesar
Lopez, Cesar Lopez DR. Eman Abdulazeem Ahmed
11
.

Result for Rocket Example

MATLAB Differential and


Integral MATLAB Differential
and Integral Calculus, Cesar
DR. Eman Abdulazeem Ahmed
Lopez, Cesar Lopez 12
Multiple data sets in one plot
❑ Multiple (x, y) pairs arguments create multiple graphs with
a single call to plot.
❑ For example, these statements plot three related functions
of
x: y1 = 2 cos(x), y2 = cos(x), and y3 = 0.5 ∗ cos(x), in the
interval 0 ≤ x ≤ 2π.
x = linspace(0,(2*pi),100);
y1 = 2*cos(x);
y2 = cos(x);
y3 = 0.5*cos(x);
MATLAB Differential and
plot(x,y1,'--',x,y2,'-',x,y3,':')
axis([0 2*pi -3 3])
Integral MATLAB Differential
and Integral Calculus, Cesar
DR. Eman Abdulazeem Ahmed
Lopez, Cesar Lopez 13
changing the appearance

❑ By default, MATLAB uses line style and


color to distinguish the data sets plotted in
the graph.
❑ However, you can change the appearance of
these graphic components or add
annotations
MATLAB to the graph
Differential andto help explain
your data
Integral MATLABfor presentation.
Differential
and Integral Calculus, Cesar
DR. Eman Abdulazeem Ahmed
Lopez, Cesar Lopez 14
Plot(x,y,…properties)

❑ Plot(x,y,cml) – plot with a basic colour-


marker-line combination (cml)
❑ Examples: ‘ro-’, ‘g.-’, ‘cv--‘

cml
MATLAB Differential and
Integral MATLAB Differential
and Integral Calculus, Cesar
Lopez, Cesar Lopez
DR. Eman Abdulazeem Ahmed 15
Plot(x,y,…properties) (cont'd.)
❑ More detailed plot options can be specified through the
use of property:value pairs
❑ Plot(x,y,’o-’,’property’,value)
‘property’ is always a string naming the propery,
value can be a number, array, or string, depending on the
property type:
‘color’ : [R G B] color is specified with a [red green blue]
MATLAB Differential
value array, and
each in range 0-1.
Integral – pure red
[1 0 0]MATLAB Differential
[1 0.5 0] – orange
and Integral Calculus, Cesar
DR. Eman Abdulazeem Ahmed
Lopez, Cesar Lopez 16
Labels
❑ Labels and titles allow for strings to be added as axis labels

❑ All three work very similarly


>> title(‘My plot’)
>> xlabel(‘Time (s)’)
>> ylabel(‘Frequency \lambda’)

❑ In addition to any string the properties of labels and title can be set
using the text properties list
MATLAB Differential and
❑Integral MATLAB
Just like every Differential
other component labels and titles should be added
before moving on to the next subplot
and Integral Calculus, Cesar
Lopez, Cesar Lopez DR. Eman Abdulazeem Ahmed
17
Example:
%%% Custom RGB colour vectors
% divide element by element on 255 to ensure the range not exceed 1
colour_teal = [18 150 155] ./ 255;
colour_lightgreen = [94 250 81] ./ 255;
colour_green = [12 195 82] ./ 255;
colour_lightblue = [8 180 238] ./ 255;
colour_darkblue = [1 17 181] ./ 255;
colour_yellow = [251 250 48] ./ 255;
colour_peach = [251 111 66] ./ 255;
%%% 1) draw solid line through data points
x = 0:0.01:2*pi;
y = sin(x);
plot(x,y, 'LineWidth', 2, 'Color', colour_teal); hold on;
%%% 2) draw just circle markers at data points, no
% connecting line (LineWidth sets width of marker edges)
MATLAB Differential and
x = 0:0.2:2*pi;
Integral MATLAB Differential
y = sin(x+(0.25*pi));
plot(x,y, 'ko', 'LineWidth', 3, 'MarkerEdgeColor',...
and Integral Calculus, Cesar
colour_green, 'MarkerFaceColor', colour_lightgreen,...
'MarkerSize', 15);
Lopez, Cesar Lopez
DR. Eman Abdulazeem Ahmed 18
Example (cont'd.):
%%% 3) draw solid line with square markers at
data points
x = 0:0.2:2*pi;
y = sin(x+(0.5*pi));
plot(x,y, '-ks', 'LineWidth',3, 'Color',...
colour_lightblue, 'MarkerEdgeColor',...
colour_darkblue, 'MarkerFaceColor', ...
colour_yellow, 'MarkerSize', 8);
%%% 4) draw thick dashed line through data
points (sometimes only renders correctly when
printing)
MATLAB Differential and
x = 0:0.01:2*pi;
Integral MATLAB Differential
y = sin(x+(0.75*pi));
plot(x,y, 'k--',
and Integral 'LineWidth',
Calculus, Cesar 5, 'Color',...
colour_peach);
Lopez, Cesar Lopez
DR. Eman Abdulazeem Ahmed See the results Next slide 19
Subplots
❑ subplot(m,n,p) : create a subplot in an array of axes

>> subplot(2,3,1);
>> subplot(2,3,2);
>> subplot(2,3,3); P=1 P=2 P=3
>> subplot(2,3,4);
m
MATLAB Differential and
P=4
Integral MATLAB Differential
and Integral Calculus, Cesar
DR. Eman
Lopez, Abdulazeem
Cesar Lopez Ahmed n 20
‘Handle’ Graphics
❑ MATLAB uses a hierarchical graphics model
❑ Graphics objects organised according to their
dependencies: e.g. lines must be plotted on axes,
axes must be positioned on figures
❑ Every object has a unique identifier, or handle
❑ Handles are returned by the creating function
❑ ax = subplot(3,2,n)
❑ H = plot(x,y)
MATLAB Differential and
❑ Handles can be used to identify an object in order to
Integral MATLAB Differential
inspect (get) or modify (set) its properties at any time
and Integral Calculus, Cesar
Lopez, Cesar Lopez DR. Eman Abdulazeem Ahmed
21
‘Handle’ Graphics Axes example
❑ To add axes properties to an existing axis use the command set
set(gca, ’box’, ’on’, ’Fontsize’, 8)
❑ Axes parameters control both the style and look of the axes as well
as things like tick marks and spacing
set(gca, ’xtick’, [0:2:10], ‘XAxisLocation’, ‘top’)

MATLAB Differential and


Integral MATLAB Differential
and Integral Calculus, Cesar
DR. Eman Abdulazeem Ahmed
Lopez, Cesar Lopez 22
Other Types of 2-D Plots
❑Polar Plots
❑ Logarithmic Plots

❑ Bar Graphs

❑ Pie Charts

❑ Histograms

❑ Function Plots
MATLAB Differentialand
Integral MATLAB Differential
and Integral Calculus, Cesar
DR. Eman Abdulazeem Ahmed
Lopez, Cesar Lopez 23
Polar Plots
❑ MATLAB provides plotting capability with polar
coordinates:
polar(theta, r)
❑ generates a polar plot of angle theta (in radians) and radial
distance r .
❑ For example, the code

x = 0:pi/100:pi;
y = sin(x);
polar(x,y)
MATLAB Differential and
❑ generates the plot in Figure 5.16 . A title was added in the
Integral MATLAB Differential
usual way:
and Integral
title('The Calculus,
sine function plotted in polarCesar
coordinates is a circle.')

Lopez, Cesar Lopez DR. Eman Abdulazeem Ahmed


24
Logarithmic Plots

❑ A logarithmic scale (base 10) is convenient


when
❑a
variable ranges over many orders of
magnitude, because the wide range of values
can be graphed, without compressing the
smaller values.
MATLAB Differential and
❑ data varies exponentially.
Integral MATLAB Differential
and Integral Calculus, Cesar
DR. Eman Abdulazeem Ahmed
Lopez, Cesar Lopez 25
Bar Graphs and Pie Charts
❑ MATLAB includes a whole family of bar graphs and pie
charts
❑ bar(x) – vertical bar graph
❑ barh(x) – horizontal bar graph
❑ bar3(x) – 3-D vertical bar graph
❑ bar3h(x) – 3-D horizontal bar graph
❑ pie(x) – pie chart
❑ pie3(x) – 3-D pie chart

MATLAB Differential and


Integral MATLAB Differential
and Integral Calculus, Cesar
Lopez, Cesar Lopez
DR. Eman Abdulazeem Ahmed 26
Example

clear, clc
x = [1,2,5,4,8];
y = [x;1:5];
subplot(2,2,1)
bar(x),
title('A bar graph of vector x')
subplot(2,2,2)
bar(y),
title('A bar graph of matrix y')
subplot(2,2,3)
bar3(y),
MATLAB Differential and
title('A three-dimensional bar graph')
subplot(2,2,4)
Integral MATLAB Differential
pie(x),
title('A pie chart of x')
and Integral Calculus, Cesar
DR. Eman Abdulazeem Ahmed
Lopez, Cesar Lopez 27
Histograms
❑ A histogram is a plot showing the distribution of a set of
values
x = [100,95,74,87,22,78,34,35,93,88,86,42,55,48];
hist(x)

MATLAB Differential and


Integral MATLAB Differential
and Integral Calculus, Cesar
DR. Eman Abdulazeem Ahmed
Lopez, Cesar Lopez 28
>> peaks;

MATLAB Differential and


Integral MATLAB Differential
Peaks is an example function, useful for demonstrating 3D
and Integral Calculus, Cesar
data, contouring, etc. Figure above is its default output.
Lopez,P=peaks;
Cesar- return
Lopez data matrix for replotting…
29
Animation
The two functions that are used to create a movie are
A(k) = getframe
which captures the kth movie frame of a total of N frames and
movie(A, nF, pbs)
which is used to play nF times the N frames captured in the matrix A
by getframe.
This function plays the movie at a playback speed pbs, which, if
omitted, uses a default value of 12 frames per second.
MATLAB Differential and
Integral MATLAB Differential
and Integral Calculus, Cesar
DR. Eman Abdulazeem Ahmed
Lopez, Cesar Lopez 30
Animation

To create a movie in the avi (audio/video interleaved) format


from the movie created by movie, one uses
movie2avi(A, 'FileName.avi', 'KeyWord',
'KeyWordValue');
The variable A is the variable used in movie.
To create movies that can be shown in Microsoft Power
Point, we set
MATLAB
'KeyWord' Differential
= 'compression' and
Integral MATLAB
'KeyWordValue' = 'none'Differential
and Integral Calculus, Cesar
Lopez, Cesar Lopez DR. Eman Abdulazeem Ahmed
31
Example – Animation of a slider-crank
mechanism
The horizontal distance that
the slider moves as a
function of the rotation angle d

 of the crank arm a is  c


e b
a f
s
s = a cos  + b − ( a sin  − e )
2 2

MATLAB Differential and


Integral MATLAB Differential
and Integral Calculus, Cesar
DR. Eman Abdulazeem Ahmed
Lopez, Cesar Lopez 32
Animation of a slider-crank mechanism

Let:
0    2 at n = 40 equally-spaced positions
a=1
b = 2.5
e = 0.25
c = 0.5
MATLAB
d = 1 Differential and
f = 0.06
Integral MATLAB Differential
The number of times that the 40 frames is to be
and repeated
Integral Calculus,
(played over) is 5 Cesar
(= nF).
Lopez, Cesar Lopez DR. Eman Abdulazeem Ahmed 33
n = 40; phi = linspace(0, 2*pi, n);
a = 1; b = 2.5; e = 0.25; nF = 5;
c = 0.5; d = 1; f = 0.06;
ax = a*cos(phi); ay = a*sin(phi);
s = real(ax+sqrt(b^2-(ay-e).^2));
v = [1.1*min(ax), 1.1*(max(s)+d/2) 1.1*min(ay), 1.1*max(ay)];
xgnd = [min(ax), max(s)+d/2, max(s)+d/2, min(ax), min(ax)];
ygnd = [e, e, e-f, e-f, e];
slidery = [e, e+c, e+c, e, e]; % Vertical component of slider is constant
d

 c

s = a cos  + b 2 − ( a sin  − e )
2
e b
a f
s

for k=1:n
fill(xgnd, ygnd, 'r') % Thin horizontal bar
hold on
plot(ax, ay, 'b--', 0, 0, 'ko'); % Dashed circle and center of circle
sliderx = [s(k)-d/2, s(k)-d/2, s(k)+d/2, s(k)+d/2, s(k)-d/2];
MATLAB Differential and
fill(sliderx, slidery, 'm'); % Slider position
plot([0 ax(k)], [0;ay(k)], 'ko-', 'LineWidth', 2);
plot([ax(k), s(k)], [ay(k), e+c/2], 'ko-', 'LineWidth', 2);
Integral MATLAB Differential
axis(v)
axis off equal
and Integral Calculus, Cesar
SliderCrankFrame(k) = getframe;
hold off
end DR. Eman Abdulazeem Ahmed
Lopez, Cesar Lopez
movie(SliderCrankFrame, nF, 30)
VideoWriter('D:\SliderCrankAvi.avi');
34
MATLAB Differential and
Integral MATLAB Differential
and Integral Calculus, Cesar
Lopez, Cesar Lopez 35

You might also like