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.



Friday, April 15, 2016

Data Classes in MATLAB

Fundamental Data Types

All data in MATLAB is in the form of a matrix or array. But the data that we use in MATLAB software are of different classes. We can make matrices and arrays of any types of these data classes. Two of the MATLAB classes, structures and cell arrays, provide a way to store dissimilar types of data in the same array. There are 15 fundamental data classes in MATLAB. We can develop our own data types. Different data types require different amounts of storage space, the smallest type is ‘logical’, which requires only 1 byte.

(Picture courtesy: www.mathworks.com)

By default, MATLAB stores all numeric variables as double-precision floating-point values and text as characters.

Numeric Data Types

Numeric data types are mainly of two types: Floating-Point Numbers and Integers. Floating point numbers are again two types:
Double – This is the default numeric data type. It uses double precision. It can be created by simple assignment operator. ‘double( )’ command is used to convert other data types to double class.
Single – Any value stored as a single requires 32 bits. ‘single( )’ command is used to convert the double type data to single data type. Requires less storage space than double.
 ‘whos’ command can be used to display the attributes including class of a variable.
‘isfloat( )’ command is used to verify that a variable is a floating-point number. It returns logical 1 if the number is a floating-point number and logical 0 otherwise.
>> a=25.456
a =
>> whos
  Name      Size            Bytes  Class     Attributes
  a         1x1                 8  double             
>> b=single(a)
b =
>> whos b
  Name      Size            Bytes  Class     Attributes
  b              1x1                 4      single             

The range for double is:
   -1.79769e+308 to -2.22507e-308 and
    2.22507e-308 to  1.79769e+308
The range for single is:
            -3.40282e+38 to -1.17549e-38 and
             1.17549e-38 to  3.40282e+38

Integer – This class is used to represent the signed and unsigned whole numbers. Based on the size used (1, 2, 4 and 8 bytes), there are four types of signed and unsigned classes.
Range of Values
Conversion Function
Signed 8-bit integer
-27 to 27-1
Signed 16-bit integer
-215 to 215-1
Signed 32-bit integer
-231 to 231-1
Signed 64-bit integer
-263 to 263-1
Unsigned 8-bit integer
0 to 28-1
Unsigned 16-bit integer
0 to 216-1
Unsigned 32-bit integer
0 to 232-1
Unsigned 64-bit integer
0 to 264-1

>> c=int16(-25.450)
c =
>> d=uint16(-25.450)
d =
>> e=int64(-25.450)
e =
>> whos
  Name      Size            Bytes  Class     Attributes
  c            1x1                 2        int16              
  d            1x1                 2       uint16             
  e            1x1                 8       int64              
>> x='Electrical'
x =
>> y=int32(x)    % int command can be used to convert other data types to integers.
y =
          69         108         101          99         116         114         105          99          97         108 


MATALB store the text as character data type. Strings are represented as vectors of characters. MATLAB identifies  the characters in single quotation marks as text and such variables are saved as character data class.
‘char( )’ command is used to convert to character array. Convert the integers between 32–127 into a the printable ASCII characters.
‘ischar( )’ is used to Determine whether item is character array
>> x='Electrical';
>> whos x
  Name      Size            Bytes  Class     Attributes
  x              1x10               20    char
Considering the variable y from the previous example, we can convert it back to text using:
>> z=char(y)
z =


The logical data type is used to store Boolean values, true or false states using the numbers 1 and 0, respectively. Output of some MATLAB functions or operators will be logical values, those variables are stored as logical data class.
‘logical( )’ - Convert numeric values to logical. Any nonzero element of A is converted to logical 1 (true) and zeros are converted to logical 0 (false).
‘islogical( )’ - Determine if input is logical array 


This data type is used to store the tables which have multiple columns of different data types. Tables consist of rows and column-oriented variables. Each variable in a table can have a different data type and a different size with the one restriction that each variable must have the same number of rows. The data may be stored or in a text file or in a spreadsheet.
Create table from workspace variables
Convert homogeneous array to table
Convert cell array to table
Convert structure array to table
Convert table to homogeneous array
Convert table to cell array
Convert table to structure array
Create table from file
Write table to file
Working with tables will be discussed in detail in another post.


Structure is a data type used to store information like a database. It groups related data using data containers called fields. Each field can contain data of any type or size. Access data in a structure using dot notation of the form structName.fieldName.
a = struct(field1 ,value1, field2 ,value2,…. ) is the syntax of command to create a structure with the specified field and values. The argument field is the name of the field and the value input argument can be any data type, such as a numeric, logical, character, or cell array.
>> field1 = 'voltage';
>> field2 = 'current';
>> value1 = [10, 20, 30];
>> value2 = [1, 2, 3];
>> vi = struct(field1, value1, field2, value2)
vi =
    voltage: [10 20 30]
    current: [1 2 3]

>> vi.voltage
ans =
    10    20    30
>> vi.current
ans =
     1     2     3
>> vi.resistance = 10
vi =
       voltage: [10 20 30]
       current: [1 2 3]
    resistance: 10 

Cell Array

A cell array is a data type with indexed data containers called cells, where each cell can contain any type of data. Cell arrays commonly contain either lists of text strings, combinations of text and numbers, or numeric arrays of different sizes.
An empty cell can be created using ‘cell( )’ command
>> C = cell(3,4)
C =
     [ ]     [ ]     [ ]     [ ]
     [ ]     [ ]     [ ]     [ ]
     [ ]     [ ]     [ ]     [ ]

A curly bracket{} operator can use the to create an empty 0-by-0 cell
>> C = {}
C =
>> D={[1 2 3]; 'text value'}
D =
    [1x3 double]
    'text value'
Refer to sets of cells by enclosing indices in smooth parentheses, (). Access the contents of cells by indexing with curly braces, {}. 

Function Handles

Function handles are the data type used to store variables that index to a function. Function handle used to construct anonymous functions or specify call back functions or call local functions from outside the main function.
To create a handle for a function, precede the function name with an @ sign.
>> magnitude = @abs;
>> magnitude(3+4i)
ans =

Wednesday, April 6, 2016

3D plots in MATLAB

MATLAB provides a lot of graphics to make quick 3-D plots. In this post we will discuss some of these functions.
The common 3D plot functions are:
·         Plot3
·         Waterfall
·         Contour3
·         Mesh
·         Surf

Some Useful Functions

Before discussing the 3D plotting functions, we will discuss some other useful MATLAB functions required to design 3D objects.
To define a third axis data, first we have to make a data set of x and y axis data. For each pair of x and y we define value of z. MATLAB provides a useful function called ‘meshgrid’ that can be used generate x-y pair for 3-D plots.
[X,Y] = meshgrid(a,b) will generate a two matrices X and Y, which contain x and y values for the x-y pair , where a and b are vectors that define the range of x and y.
>> a = [-1 0 1];
>> b = [9 10 11 12];
>> [X,Y] = meshgrid(a,b)
X =
    -1     0     1
    -1     0     1
    -1     0     1
    -1     0     1
Y =
     9      9      9
    10    10    10
    11    11    11
    12    12    12
ndgrid and meshgrid are similar, the difference is that ndgrid will make a N dimensional grid. The dimension of the output is determined by the number of output arguments.
The syntax is [X1,X2,X3,...] = ndgrid(x1v,x2v,x3v,...)
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.
cylinder(R,N) plots a unit height cylinder of radius R. The cylinder has N points around the circumference. Default value of N is 20.
sphere(N) generates three (N+1)-by-(N+1) matrices which define the points to make a unit sphere and graph the sphere as a SURFACE. Default value of N is 20.
peaks is a function of two variables, obtained by translating and scaling Gaussian distributions, which is useful for demonstrating MESH, SURF, PCOLOR, CONTOUR, etc.


The plot3 command is used to plot the lines and points in a three dimensional space. It is used in the same way as plot function is used. Plot3 will have a third variable to provide the third dimension data. To label the third axis, ‘zlabel’ command is used.
plot3(x,y,z) creates a three dimensional plot where x, y & z are equal sized arrays containing the locations of data points  to be plotted.
>> t = 0:pi/50:10*pi;
>> plot3(sin(t),cos(t),t)


Mesh Plot

mesh(x,y,z)command produces wireframe surfaces in three dimensions that color only the lines connecting the defining points.
>> [x,y] = meshgrid(-1:.1:1);
>> z = x.^2+y.^2;
>> mesh(z)

meshz(x,y,z) draws a curtain around the wireframe mesh.


The waterfall function draws a mesh similar to the ‘meshz’ function, but it does not generate lines from the columns of the matrices. This produces a "waterfall" effect.
The waterfall plot for the above example will be:
>> waterfall(z)

Ribbon Plot

The ribbon(z) command plots the curve of z along y axis with ribbons of uniform width and midpoint as elements of x.
>> ribbon(z)

Surface Plots

surf(x,y,z) creates three dimensional plot that colors both the connecting lines and the faces of the surface. The color will be selected from default color map unless it is defined by an argument.
>> [X,Y,Z] = sphere(100);
>> surf(X,Y,Z)

surfc(x,y,z) creates a surface plot and a contour plot under the surface plot.

Ezsurf command can be used to plot a surface plot of a function. The function z=x2+y2 can be plot using the command:
>> ezsurf('x.^2+y.^2', [-1 1])


contour(x,y,z)command constructs a three dimensional contour plot. The counters are normally based on the current color map. z defines the heights with respect to the x-y plane. The level of contour lines is chosen automatically.
>> contour3(z)

The color level lines can be controlled by adding one more argument in the command. contour(z,n) command will plot the curve with ‘n’ color levels. The levels at which the lines has to be drawn can be defined by a vector ‘v’ as, contour(z,v). clabel(‘text’) command is used to label the contour lines.

3D Stem Plots

stem3 creates vertical lines terminated with a symbol in x-y plane.
stem3(Z) plots the discrete surface Z as stems from the xy-plane terminated with circles.
stem3(X,Y,Z) plots the surface Z at the values specified in X and Y.
>> theta = 0:.2:2*pi;
>> x=sin(theta);
>> y=cos(theta);
>> z=sin(theta);
>> stem3(x,y,z)
>> hold on
>> plot(x,y)


Color Shading of Plots

shading is a MATLAB command that sets the EdgeColor and FaceColor properties of all SURFACE objects in the current axes. It sets them to the correct values that depend upon whether the SURFACE objects are representing meshes or surfaces.  
shading flat sets the shading of the current graph to flat. Color of the line will be same as the Color at the end point of the segment.
shading interp sets the shading to interpolated. Color in each segment or patch varies linearly and interpolates the line color
shading FACETED sets the shading to faceted (default). Flat shading with superimposed black mesh lines.

Changing View Angle

view command is used to change the view angle of the 3D objects.     
view(AZ,EL) or view([AZ,EL]) is the syntax to set the view angle. AZ is the horizontal rotation angle in degree. A positive value indicate counter-clock wise rotation. EL is the vertical elevation in degrees. Positive values of elevation indicate moving above object and negative values move below.
view([X Y Z]) sets the view angle in Cartesian coordinates.
AZ = -37.5, EL = 30 is the default 3-D view. view(3) is used to set the default 3-D view.
AZ = 0, EL = 90 is the values for ‘Top View’. view(2) is used to get the top view.
>> t = 0:pi/50:10*pi;
>> subplot(1,3,1)
>> plot3(sin(t),cos(t),t)
>> title('default view')
>> subplot(1,3,2)
>> plot3(sin(t),cos(t),t)
>> view(2)
>> title('top view')
>> subplot(1,3,3)
>> plot3(sin(t),cos(t),t)
>> view(90,0)
>> title('front view')