Click here to load reader
Date post: | 29-Jun-2015 |
Category: |
Technology |
Upload: | waleed-usman |
View: | 370 times |
Download: | 1 times |
Click here to load reader
2. MATLAB Dr. Kashif Mahmood Rajpoot
SEECS, NUST Islamabad [email protected]
NUST Science Society (NSS) Workshop
Workshop Contents: Session 2
• Cell and Structure Arrays
• Plotting: 2D plots – legend, title, xlabel, ylabel, subplot, stem, barh, comet, area, imagesc, etc. 3D plots – surf, mesh
• Symbolic Math
Cell and Structure Arrays
• Data structures – variables that hold more than one value – Multiple values which are logically related
• Hold values of same type (e.g., vector, matrix)
• Hold values of different type (e.g., cell, structure) – Cell arrays – multiple values are placed as elements of
the array
– Structure arrays – multiple values are stored as fields of the structure • i.e., each value has its own name
Cell arrays
• Cell array is an array, but unlike vectors and matrices, the elements of cell array can store different types of values
• Cell array is a special MATLAB array whose elements are cells i.e. containers that can hold other MATLAB arrays – Not found in many languages other than MATLAB
• Each cell element is actually a pointer to another data structure which can be a vector, a matrix, a string, a char, etc.
• Cell arrays – provide a way to collect different types of data
Cell arrays
Cell array – creation
• Creating cell arrays
– By using assignment statements
– By pre-allocating a cell array using cell function
• Creating cell array using assignment statements
– Content indexing – directly accessing contents of a cell
– Cell indexing – accessing the cell container
Cell array – creation • Involves placing curly braces ‘,-’ around cell
subscripts, together with cell contents in ordinary notation
a{1, 1} = [1 3 -7; 2 0 6; 0 5 1];
a{1, 2} = 'This is a text string';
a{2, 1} = [3+4*i -5; 10*i 3-4*i];
a{2, 2} = [];
Using data in cell arrays
• Data inside a cell array can be accessed anytime using cell indexing
c=,*1 2;3 4+, ‘dogs’; ‘cats’, i};
c{1,1}
c{2,1}
• Subsets of a cell content can also be accessed
c{1,1}(1,2)
Cell arrays of strings
• It is very convenient to store groups of strings in a cell array
– E.g., title labels in the last lecture on plots
– Each string can have a different length
titles,1- = ‘Plot’
titles,2- = ‘Area’
titles,3- = ‘Stem’
Structure arrays
• In a typical array data structure, there is one name for whole data structure and the individual elements are accessed by referring to the element number – E.g., arr(5) refers to ??
• In contrast, structure array is a data type where each individual data element has a distinct name – Each element of the structure is called a field – Each field of the structure can have a different type – Individual fields are accessed by structure.field
pattern
Structure array – creation
• Using assignment statement
Student.name = ‘John Doe’;
Student.address = ‘123 Main Street’;
Student.city = ‘Any city’;
• A second student can be added to the structure by adding a subscript to the structure name (before the period)
Student(2).name = ‘Jack Gill’;
Structure array – adding fields
• Whenever a field is added to the structure, the field is added automatically to all the elements of the structure array
Student(2).marks = [90 82 88];
– This field will be initialized to an empty value for all the other elements of structure array
Using data in structure arrays • Data can be accessed from any field using 3
components:
– Structure_name(index).field_name
Plotting • MATLAB has extensive device-independent
plotting capabilities
– Very simple and easy to plot data
x=0:1:10;
y=x.^2-10.*x+15;
plot(x,y);
• Any pair of vectors can be plotted using this procedure as long as both vectors have same length
Plotting – Grid, Label, Title, Save
• Additions to the plot – grid on
– grid off
– xlabel
– ylabel
– title
• Saving a plot – File->Save As
– Save type (BMP, JPG, etc.)
Plotting – Multiple Plots
f(x)=sin2x
f’(x)=2cos2x
x=0:pi/100:2*pi;
y1=sin(2*x);
y2=2*cos(2*x);
plot(x,y1,x,y2)
• Alternative way for multiple plotting – hold on, hold off
Plotting – Line Color, Marker Style, Legends • Line color and marker style can be chosen x=0:1:10; y=x.^2-10.*x+15; plot(x,y, ‘r--’, x, y, ‘bo’); • Legend can be created with legend function to add
description to the graph – legend(‘string1’, ‘string2’, ..., pos)
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)=sin2x and its derivative’); xlabel(‘x’), ylabel(‘y’) legend(‘f(x)’, d/dx f(x)’) grid on
Plotting
• Graph plotting provides us with a mechanism to visualize numerical data\information (e.g., sine, temperature, marks, image, etc.) for a simple analysis about the behavior of a function
• MATLAB provides numerous built-in functions to do plotting in 2D and 3D – 2D – plot, bar, hbar, stem, stairs, pie, comet, hist
– 3D – mesh, surf
2D plotting • Plotting one dependent variable (y) against an
independent variable (x)
• Stem plot – each data value is represented by a marker and a line connecting that marker vertically with x-axis
• Stair plot – each data value is represented by a horizontal line and successive points are connected by vertical lines
• Bar plot – each point is represented by a vertical bar • Horizontal bar plot – each point is represented by a
horizontal bar • Pie plot – represents “pie slices” of various sizes • Area plot – draws the plot as a continuous curve and
fills in the area under the curve
Stem plot
x=[1 2 3 4 5 6]
y=[2 6 8 7 8 5]
stem(x, y);
title(‘\bfExample of a stem plot’)
xlabel(‘\bf\itx’)
ylabel(‘\bf\ity’)
axis([0 7 0 10])
Subplot: ‘matrix’ of plots
• How to draw more than one plot on same figure window?
subplot(rows, columns, ind)
• Creates a ‘matrix’ of plots on a figure window
Subplot: ‘matrix’ of plots
%demonstrates subplot using a for loop for i = 1:2 x = linspace(0,2*pi,10*i); y = sin(x); subplot(1,2,i) plot(x,y,'k-o') ylabel('sin(x)') title(sprintf('%d Points',10*i)) end
Subplot and 2D plotting x=[1 2 3 4 5 6]; y=[2 6 8 7 8 5]; subplot(3,3,1), plot(x, y), title('\bfPlot'), axis([0 7 0 10]) subplot(3,3,2), stem(x, y), title('\bfStem plot'), axis([0 7 0 10]) subplot(3,3,3), stairs(x, y), title('\bfStair plot'), axis([0 7 0 10]) subplot(3,3,4), bar(x, y), title('\bfBar plot'), axis([0 7 0 10]) subplot(3,3,5), barh(x, y), title('\bfBar-h plot'), axis([0 10 0 7]) subplot(3,3,6), pie(y), title('\bfPie plot') subplot(3,3,7), pie(y, ones(size(y))), title('\bfPie plot') subplot(3,3,8), area(x, y), title('\bfArea plot'), axis([0 7 0 10])
• Could we produce these subplots using a loop? % Demonstrates evaluating plot type names in order to % use the plot functions and put the names in titles x = 1:6; y = [33 11 5 9 22 30]; titles = {'bar', 'barh', 'area', 'stem'}; for i = 1:4 subplot(2,2,i) eval([titles{i} '(x,y)']) title(titles{i}) end
Subplot and 2D plotting
Pie chart with labels
pie ([3 10 5 2])
pie([3 10 5 2], {'A','B','C','D'})
Histogram plot
• A plot showing the distribution (i.e., frequency) of values within a data set
– The range of values with the dataset is divided into evenly spaces bins (i.e., intervals) and the number of values falling into each bin is found
– Result is plotted as a function of bin number
y=randn(10000,1);
hist(y,15);
Animation
x = -2*pi : 1/100 : 2*pi;
y = sin(x);
comet(x,y)
• Comet – plots the trail of the function from the 1st to the last point to draw animation
– Plots point (x(1),y(1)), then (x(2),y(2)), and so on..
3D plotting
• 3D plots are useful for creating two types of data:
– Two variables that are function of the same independent variable (e.g., temperature and pressure changing with time)
– A single variable that is function of two independent variables (e.g., temperature changing with time and space)
3D line plot
• This function might represent the decaying oscillations of a mechanical object in two dimensions
• x and y together represent the location of object at any given time
• x and y are function of the same independent variable t
3D line plot
• We can plot x and y as a 2D plot
t=0:0.1:10;
x=exp(-0.2*t) .* cos(2*t);
y=exp(-0.2*t) .* sin(2*t);
plot(x,y)
title(‘\bf2D line plot’)
• This does not show the change in x and y with t
3D line plot • Why not plot it as a 3D line plot? t=0:0.1:10; x=exp(-0.2*t) .* cos(2*t); y=exp(-0.2*t) .* sin(2*t); plot3(x,y,t) title(‘\bf3D line plot’) xlabel(‘\bfx’) ylabel(‘\bfy’) zlabel(‘\bfz’) axis square grid on
3D mesh and surface plots
• Mesh and surface plots show data that is a function of two independent variables
– e.g. temperature changing with time and space
• Any value that is a function of two independent variables can be displayed on a 3D mesh or surface plot
3D mesh and surface plots
• Plot 4 points: (-1, -1, 1), (1, -1, 2), (-1, 1, 1), and (1, 1, 0)
3D mesh and surface plots
• MATLAB function meshgrid allows easy way to create the x and y required for computing and plotting z
• [x, y] = meshgrid(xstart:xinc:xend, ystart:yinc:yend);
[x,y] = meshgrid(-4:0.2:4, -4:0.2:4); z=exp(-0.5*(x.^2 + y.^2)); subplot(1,2,1), mesh(x,y,z), title('\bfMesh plot') xlabel('\bfx') ylabel('\bfx') zlabel('\bfz') subplot(1,2,2), surf(x,y,z), title('\bfSurface plot') xlabel('\bfx') ylabel('\bfx') zlabel('\bfz')
Symbolic Math
• Doing maths on symbols (i.e. not numbers)
– Similar to how we evaluate it on paper
– e.g. what is a+a?
• Symbolic math is supported by Symbolic Math Toolbox in MATLAB
• Example
– b = sym(‘x^2’)
– b+sym(‘4*x^2’)
Symbolic Math
• sym function
– E.g. b=sym(‘x^2’)
– Create symbols for use in symbolic math
• syms
– Create math symbols
Symbolic Math
• Simplification
syms x
expr = cos(x)^2+sin(x)^2
simplify(expr)
• collect function
• expand function
• factor function
Symbolic Math
• solve function
– Solves algebraic equation
• diff function
– Perform differentiation on symbols
• int function
– Perform integration on symbols