A blog to help electrical engineers and students to learn electrical engineering topics. Basic Electrical Engineering, Power Systems, Electrical Machines, tec.. Now special course on MATLAB for Beginners.

Class

Class

Thursday, March 31, 2016

More on Plotting - Part 3



ezplot

ezplot   is an easy to use function plotter. The limits of the plot will be automatically set by the MATLAB when you run the command.
>> ezplot('sin(t)')
You can set the limits of the function;
ezplot(‘function’,[lower_limit upper_limit]).
The command plots the function between the limits specified.
>> ezplot('sin(t)',[0 4*pi])

Ezplot can be used to plot curve between two functions.
ezplot(‘function1’,’function2’, [lower_limit upper_limit])
The command plots function1(t) versus function2(t)  over lower_limit < t < upper_limit.
>> ezplot(’cos(t)’, ’sin(t)’, [0 2*pi]); axis square
You may also use a function handle to an existing function. Function handles are more powerful and efficient than string expressions.
>> ezplot(@cos,@sin)
The command will give same plot as ezplot(’cos(t)’, ’sin(t)’, [0 2*pi]).
(About function handles we will discuss later)

Contour Plots

contour(Z) draws a contour plot of matrix Z in the x-y plane, with the x-coordinates of the vertices corresponding to column indices of Z and the y-coordinates corresponding to row indices of Z. The contour levels are chosen automatically.
A contour plot of a function of two variables is a plot of the level curves of the function, that is, sets of points in the x-y plane where the function assumes a constant value. For example, the level curves of x2 + y2 are circles centered at the origin, and the levels are the squares of the radii of the circles.
We can make a contour plot of x2 + y2 as follows:
>> [x y] = meshgrid(-1:0.1:1, -1:0.1:1); % meshgrid is used to make grid of defined points.
>> contour(x, y, x.ˆ2 + y.ˆ2)

Field Plots

The MATLAB routine quiver is used to plot vector fields or arrays of arrows. The arrows can be located at equally spaced points in the plane (if x and y coordinates are not given explicitly), or they can be placed at specified locations.
quiver(U,V) plots velocity vectors at equally spaced points in  the x-y plane.
The following code, for example, plots a vector field similar to the magnetic field near a magnetic dipole.
>> [x,y] = meshgrid(-1:.1:1,-1:.1:1);
>> z=x.*exp(-x.^2 - y.^2);
>> [a b] = gradient(z);
>> quiver(a,b)
  

Scatter Plot

scatter(x, y, size, color) displays colored circles at the locations specified by the vectors x and y (which must be the same size).  ‘Size’ determines the size of each circle marker and ‘color’ defines the color of the marker.
scatter(x, y)  will plot the markers with default size and color.
Size can be a scalar or a vector the same length as x and y. If size is a scalar, MATLAB draws all the markers the same size. If it is empty, the default size is used. If size is a vector, each marker will take a size corresponding to value specified in the vector. Color also may be a vector, then the values in color vector are linearly mapped to the colors in the default colormap (colormap is RGB color lookup table of MATLAB).
>> x = -1:0.1:1;
>> y = x.^2;
>> s = 1:21;
>> c = s;
>> scatter(x,y,s,c)

Compass Plot

compass(U,V) draws a graph that displays the vectors with components (U,V) as arrows starting from the origin.
compass(Z) is equivalent to compass(REAL(Z),IMAG(Z)).
This plot is very useful to represent the phasors.
>> v=3+4i
>> i=2-1i
>> compass(v)
>> hold on
>> compass(i)

Area Plot

Area plot is used to plot a filled 2D plot. The graph displays elements in Y as one or more curves and fills the area under each curve. The plot will be same as the ‘plot’ command, but the area between the x axis and the curve will be filled in with color.
>> x=0:10;
>> y=2.*x-1;
>> area(x,y)
>> xlabel('x value')
>> ylabel('y values')
>> title('area plot example')

Filled Shapes

fill(x, y, 'c') command can be used to draw filled polygons. The function plots a 2D polygon defined by the column vectors x and y and fills with the color specified by c. The vertices of the polygon are specified by the pairs (xi, yi). If necessary, the polygon is closed by connecting the last vertex to the first. Like the plot function, fill can have any number of pairs of vertices and associated colors.
>> x=[-1 0 1];
>> y=[0 1 0];
>> fill(x,y,'r')

Bar Graph

bar(x, y) or bar(y) command is used to plot the bar graph. It plots bars for each value of x, the height as y. If only one vector as argument, the graph will be plotted against the length of the vector.
bar(x,y, width) or bar(y, width) specifies the width of the bars. Values of width > 1 produce overlapped bars.  The default value is 0.8
>> x=0:10;
>> y=2.*x-1;
>> bar(x,y)
>> title('bar plot example')
  

Histogram Plot

Histogram plots are used to represent the distribution of a variable with in a range.
hist(z) command produces a histogram bar plot of values of z for a default 10 division of toral range.
hist(z, n) produces a histogram bar plot of values of z for n equal divisions
>> z=rand(1,100)
>> hist(z)
>> xlabel('z value')
>> ylabel('frequency of z')
>> title('histogram example')

histogram(z) creates a histogram plot of z. The histogram function uses an automatic binning algorithm that returns bins with a uniform width, chosen to cover the range of elements in z.

Pie Charts

Standard pie charts can be created by using the pie(x) function, where x is a vector of values.
pie(x, b) used to plot pie chart and pull out a specific section of the pie chart, where b is the logical vector describing a slice or slices to be pulled out of the pie chart. The pie3 function is used to draw the pie chart with a 3-D appearance.
>> x=rand(1,6);
>> pie(x)
>> title('Example Pie Chart')

>> pie(x,x==max(x))    % pulls out the slice of maximum share
>> title('Example Pie Chart')


Saturday, March 19, 2016

Plotting in MATLAB - Part 2



Controlling Axis Properties

The limits and scale of a plot will be automatically set by the MATLAB when you run a plot command. There are commands defined to change this default values. The common commands used for axis scaling and appearance are given below.
axis([xmin xmax ymin ymax]) command sets scaling for the x- and y-axes on the current plot. This command is useful to display a specific area of a plot. 
Example: axis([0 20 0 100]).
axis auto  - returns the axis scaling to its default, automatic mode
axis off  - turns off all axis labeling, tick marks and background.
axis on   - turns axis labeling, tick marks and background back on.
axis equal – makes both axes equal division
axis square - Sets axis region to be square.
axis tight - Sets the axis limits to the range of the data.
grid on  -  Adds grid lines to the plot.
grid off  - Removes grid lines from the plot.

Formatting the Text in Plots

The text displayed in the plots can be formatted by adding the property name and values following the string. The formatting can be used to define the font, size, superscript, subscript, italic, bold, and color of the characters, the color of the background, and many other properties. Font style can be formatted by adding the ‘modifiers’ in the string. These modifiers affect the text from the point at which they are inserted until the end of the string. If the modifier is required for a section only, then type the modifier and the text to be affected inside braces { }.
\bf - bold font
\it - italic style
\rm - normal font
_  - subscript (only one character)
^  - superscript (only one character)
For subscript and superscript, if we need to apply for more characters, put them in braces { }.
Syntax to define properties is
text(x,y,‘Your Text Here’,PropertyName, PropertyValue)
Example:
xlabel(‘d_2-d_1’)        displays x label as d2-d1
ylabel(‘x^2’)                displays y label as x2
title('\fontname{Arial}Plot of x^2','FontSize',14)  displays title in Arial font with size 14
text(pi/2,1,'\it This is the maxima of the function.','EdgeColor','r','LineWidth',2)  displays the text in the plot in italic font with the defined properties.

Typing Greek Characters

The Greek characters can be used in the strings by typing their codes following a \. The commands are given below.
α          \alpha
β          \beta
γ          \gamma
θ          \theta
Ï€          \pi
σ          \sigma
Φ         \Phi
Δ          \Delta
Ω         \Omega

Plotting a Function

The fplot command is used to plot a function y = f(x) between given limits. The function can be specified as a text string writing, and the limits inside the square bracket.
fplot(‘function’,[limits],‘line specifiers’)
The function can be a Matlab built in function or a user defined function on independent variables. The line specifiers are same as in the plot.
fplot('sin(x)',[-2*pi,2*pi])
Will plot sine wave for the specified period.

Logarithmic Plots

Logarithmic plots are very important in engineering analysis. MATLAB commands to plot logarithmic curves are given below.
semilogy(x,y)    Plots y versus x with a log10 scale for the y axis and linear scale for the x axis.
semilogx(x,y)    Plots y versus x with a log10 scale for the x axis and linear scale for the y axis.
loglog(x,y)        Plots y versus x with a log (base 10) scale for both axes.

(picture courtesy: MATLAB an Introduction, Amos Gilat)

Polar Plots

The polar command is used to plot functions in polar coordinates. The syntax is
polar(theta,rho)
where the angle of vector is theta, in radians, and the radius is rho.
Example
>> t = linspace(0,2*pi,1000);
>> polar(t,sin(2*t))


Plotting Complex Data

When the arguments to plot are complex, the imaginary parts are ignored, except when the plot is given in single complex argument. For this case the plot is done between the real and imaginary parts. If z is a complex variable, plot(z) is same as plot(real(z), imag(z)).
Example
>> t= linspace(0,2*pi,1000);
>> z=exp(i*t);
>> plot(z)
>> axis square


Saturday, March 12, 2016

Graphics in MATLAB - Basics



Introduction

Graphical representation of problems is very important in engineering problem solving. Plotting the results usually leads to additional insight into the nature of the problem.  So plotting is an important element to use and become skilled at using with MATLAB.
MATLAB has an excellent set of graphic tools.  Plotting a given data set or the results of computation is possible with very few commands.  You may need multiple plots to occur in a single window, or multiple windows to plot your functions.  You will be able to label the axis, label the graph, choose colors and symbols for the plot, or use the default axis and colors.  If you have created a plot, and then enter a second plot command, the first plot will be overwritten unless you type some special commands to keep the current plot or create a second Graphics Window.

Basic Plotting

The MATLAB command to plot a graph is plot(x,y). A graphics window with a plot of vector y versus vector x appears in response to this command. For each element of vector x, a y value must me defined (both x and y are either row vector s or column vector s of the same length).

Example
>>x=linspace(0,4*pi,100);
>>y=sin(x);
>>plot(x,y)
Figure 1 Plot for the vectors x and y=sin(x)

If y is a vector, plot(y) produces a piecewise linear graph of the elements of y versus the index of the elements of y. (In this example there are 100 elements in the vector y)
Figure 2: Plot for the vector y

The Plot Command

The syntax for linear plot command is
plot (x, y, ‘color style marker’, ‘PropertyName’, PropertyValue )

The color, style and marker values are optional to define the properties of the line. The color of a single curve is, by default, blue. If required these properties are typed inside a single quote. The letters used to define each property is given Table 1 below. Also the PropertyName and PropertyValue parameters are optional and are used to specify the line width, marker size and edge, fill color, etc. First type property name in quote marks and type the value after a comma. The list of available properties is given in Table 2.

Table 1 - Color Marker Style Properties and Codes
 

Table 2 - Other Plot Properties

Example
>> plot(x,y,'mx:')
Figure 3 - Plot with Color-Magenta, Marker-x and style dotted

>> plot(x,y,'gh-.')
Figure 4 - Plot with Color-Green, Marker-hexagon and style dash-dot

Adding Title, Axis Label, Legend,…

Title, labels, etc. can be easily added to the plot using simple commands. The common commands are listed below.
X-axis label.
 xlabel('text') adds text beside the X-axis on the current plot.

Y-axis label.
ylabel('text') adds text beside the Y-axis on the current plot.

TITLE
title('Some text') writes title above plot

TEXT
text(x,y,'Some text') places text in figure with first character at (x,y)

LEGEND
legend('text1','text2',...) writes legend - For each graph (data set) displays short line in same style as graph line and adds specified text.

Example
>> x=linspace(0,4*pi,100);
>> y=sin(x);
>> plot(x,y)
>> xlabel('x (secs)')
>> ylabel('sin(x)')
>> title('plot of sine function')
>> text(pi,0,'zero crossing')
>> legend('sine')
Figure 5. Plot with title and labels

Plot Two or More Curves on Same Window

More than one plot can be drawn on the same figure window.  This can be done in different ways. 

The hold command can be used to keep the existing graph and draw a new curve on the same figure window.
hold on  - holds the current plot and all axis properties so that subsequent graphing commands add to the existing graph.
hold off  - returns to the default mode
hold - toggles the hold state.

Example
>> t=linspace(0,2*pi,100);
>> x= sin(t);
>> y= cos(t);
>> z= tan(t);
>> plot (t,x)
>> hold on
>> plot(t,y)
>> legend('sine','cose')
Figure 6 Multiple plots using HOLD command

Multiple (x, y) pairs arguments can create multiple graphs with a single call to plot.
plot(x, y, u, v, t, h) plots y vs. x, v vs. u, h vs. t. Vectors of each pair must be same size but can be different than sizes in other pairs.

Example
The curves in the previous example can be plot by
>> plot(t,x,'-b', t,y,'--r',t,z,'g:')
>> xlabel ('time')
>> ylabel('trignemetric functions')
>> title('Multiple curves in a plot')
>> legend('sine(t)','cose(t)','tan(t)/10')
Figure 7. Typical example of multiple plots using single plot command

Line(x,y) command adds additional lines in vectors x and y to an existing plot. The x,y pair can be followed by parameter/value pairs to specify additional properties of the lines.
line(x,y,'PropertyName','PropertyValue')

Example
>> plot (t,x)
>> line(t,y)
Figure 8. Example of use of line command (Note: line command use the default color if not specified)

subplot(m, n, p)  command can be used to break the figure window into an m-by-n matrix of small axes and draw different curves in each section  specified by third argument p.

Example
>> x=-10:10;y=x;z=x.^2;s=x.^3;k=10.^x;  
>> subplot(2,2,1), plot(x, y)
>> subplot(2,2,2), plot(x, z)
>> subplot(2,2,3), plot(x, s)
>> subplot(2,2,4), plot(x, k)
Figure 9. Subplot example


Saturday, March 5, 2016

Managing Strings in MATLAB



Introduction

A string is an array of characters. A character string can be created in MATLAB using single quotes ('). The assignment operator is used to assign the string to a variable. For example,
>> a = 'Electrical'
a =
          Electrical
MATLAB will consider this as a 1-by-10 character array. A string can have letters, digits, symbols, spaces. To type single quote in string, use two consecutive single quotes.
Examples:  'aB  ef', '3%fr2', 'abcd:21!', 'MATLAB', 'Allen''s book'
A one line string will be considered as a row vector. If the string contain numbers, that also will be considered as characters. Number of elements in vector is number of characters in the string.
>> b = 'Electrical Engineering';
>> size(b)
ans =
          1 22
Color in code in editor
When you start type a string with a single quote it is colored maroon. When you complete the string with the closing quotation mark ('), it becomes purple.

Strings with Multiple Lines

A MATLAB variable can store strings with multiple lines as an array. This can be done similar the way we enter the matrices. The strings are entered in the square matrix and each string is separated by semi colon (;), but each line must have the same number of characters. If the lengths are not same, the remaining space must be padded with extra characters (usually spaces) to match with the longest string before closing the single quote.
>> c = [ 'Electrical'; 'Engineering' ]
??? Error using ==> vertcat
CAT arguments dimensions are not consistent.
>> c=[ 'Electrical '; 'Engineering' ]
c =
Electrical
Engineering
>> size(c )
ans =
          2 11
We can use ‘char’ function, which pads each line on the right with enough spaces so that all lines have the same number of characters
char('string 1', 'string 2', 'string 3')

Concatenation

Concatenation with square brackets joins text variables together into larger strings. The statement below joins two strings horizontally
a= 'Electrical'
d = [a, ' Engineering']     % note the space before E, used for space between the words. If space is not required don’t put the space.
d =
Electrical Engineering
The statement below joins the strings vertically
>> e = [a,' '; 'Engineering']
e =
Electrical
Engineering
Note the blank (‘ ‘) inserted after a, before the semi-colon. This space is important to make both strings have the same length.
The ‘char’ function can be used for vertical concatenation also.
>> f=char('Electrical', 'Engineering', 'Tutorial')
f =
Electrical
Engineering
Tutorial 
First and third rows above have enough space characters added on ends to make each row 11 characters long

Indexing in String

Strings are indexed the same way as vectors and matrices
      Can read by index
      Can write by index
      Can delete by index
Consider the string a='Electrical',
>> a(1)
ans = E
>> a(7:end)
ans = ical
>> a(7) =’o’
a =
Electrocal
>> a(8:end) = []
a=
          Electro
>> a(end+1:end+4) = 'nics'
a =
Electronics

String Comparison

There are several ways to compare strings and substrings:
  • You can compare two strings, or parts of two strings, for equality.
  •  You can compare individual characters in two strings for equality.
  • You can categorize every element within a string, determining whether each element is a character or white space.

strcmp is the function for comparing strings for equality. strncmp determines if the first n characters of two strings are identical. strcmpi function compares the strings without sensitivity to letter case.
Syntax is
x = strcmp('str1', 'str2')
x = strcmp('str', C)

strcmp('str1', 'str2') compares the strings str1 and str2 and returns logical 1 (true) if they are identical, and returns logical 0 (false) otherwise. str1 and str2 can be character arrays of any dimension, but strcmp does not return true unless the sizes of both arrays are equal, and the contents of the two arrays are the same.

strcmp('str', C) compares string str to the each element of cell array C, where str is a character vector (or a 1-by-1 cell array) and C is a cell array of strings. The function returns a logical array that is the same size as C and contains logical 1 (true) for those elements of C that are a match, and logical 0 (false) for those elements that are not. The order of the first two input arguments is not important.
Examples
strcmp('Electrical', 'Electrical')
ans =
     1
strcmp('Electrical', 'Electronics')
ans =
     0
g = {'Electrical';'Engineering'};
h = {'Electronic';'Engineering'};
strcmp(g, h)
ans =
    0 
1        

Other Function on Strings

char
char(x) converts the array x that contains nonnegative integers representing character codes into a character array. Char function is used to vertically concatenate the strings.

lower
lower('str') is used to convert any uppercase characters in str to the corresponding lowercase characters leaving all other characters unchanged.
>> lower('Electrical Engineering')
ans =
electrical engineering

upper
upper('str') is used to convert any lowercase characters in str to the corresponding uppercase characters leaving all other characters unchanged.
>> upper('Electrical Engineering')
ans =
ELECTRICAL ENGINEERING

blanks         Create a string of blank characters
  
mat2str - convert matrix to string
str = mat2str(A) converts matrix A into a string
str = mat2str(A,n) converts matrix A using n digits of precision.

str2num – convert ASCII character to corresponding numeric value also converts string matrices to numeric matrices.
x = str2num('str') converts the string str (ASCII character representation of a numeric value) to numeric representation.

Functions for identifying parts of strings

ischar          Determine whether item is character array
isletter         Array elements that are alphabetic letters
isspace        Array elements that are space characters