Plotting


>> This is a little bit advanced topic, In this lecture we will learn about plotting in MATLAB. It is very easy. For plotting we just use simple plot function 'plot(x,y)'. Where x the range of values for which the function is to be plotted and y is the function. Example:


x = [0:0.1:52];

y = 0.4*sqrt(1.8*x);

plot(x,y)


When you hit enter a new window is pop up which shows the graph as shown in pic below. Click the image.




See very simple.

Nomenclature for a typical xy plot:


MATLAB allows you to add tittle, labels along the x-axis and y-axis etc to make your graph more descriptive. Some commands is shown in figure.




Grid Command:


The grid command displays grid lines (like mesh) at the tick marks corresponding to the tick labels. Type grid on to add grid lines. Type grid off to stop plotting grid lines.

Axis Command:

You can use the axis command to override the MATLAB selections for the axis limits. The basic syntax is axis( [ xmin xmax ymin ymax]). you can set x-axis and y-axis range from this command. This command sets the scaling for the x- and y-axes to the minimum and maximum values indicated. Note that, unlike an array, this command does not use commas to separate the values.


Title and label commands:


The title command allows you to put a title on the graph. And xlabel and ylabel commands generate labels along x-axis and y-axis.

Example:

click image to see example




Subplot command:

Subplot command is used to obtain several smaller “subplots” in the same figure. The syntax is subplot(m,n,p). Here m is number of rows, n is number of columns and p is the number which tell where to put graph. This command divides the Figure window into an array of rectangular panes with m rows and n columns. For example, subplot(3,2,5) creates an array of six panes, three panes deep and two panes across, and directs the next plot to appear in the fifth pane (in the bottom-left corner).

Example:


Here subplot(1,2,1) means it generate an array of first row and second column and placed x and y graph to first row and first column. Now for subplot(1,2,2) means it generate an array of first row and second column and placed x and z graph to first row and second column. Click the image to view.


Note: In this example the command abs() is used. Its purpose is to take the absolute value




Plotting Polynomials with the polyval Function:

polyval is the built in command for graphing the polynomial function.


Example:




Data Markers and Line Types:


To plot y versus x with a solid line and u versus v with a dashed line, type plot(x,y,u,v,’--’), where the symbols ’--’ represent a dashed line. 

To plot y versus x with asterisks (*) connected with a dotted line, you must plot the data twice by typing plot(x,y,’*’,x,y,’:’). 


To plot y versus x with green asterisks (*) connected with a red dashed line, you must plot the data twice by typing plot(x,y,’g*’,x,y,’r--’).

Specifiers for data markers, line types, and colors:


Some of data marker, line types and colors shown in figure below. Click to see.




Labeling Curves and Data:

When more than one curve or data set is plotted on a graph, we must distinguish between them. If we use different data symbols or line types, then we must either provide a legend. To create a legend, use legend command. The basic form of this legend is 
>> legend(‘string1’, ‘string2’) 
% string1 and string2 are text strings of your choice.

The legend command automatically obtains from the plot the line type used for each data set and displays a sample of this line type in the legend box next to the string you selected.


Example:


A example is shown in figure below click to see.




Plot the Complex Numbers:

With only one argument, say plot(y) the plot function will plot the values in the vector y versus their indices 1,2,3...... and so on. If y is complex plot(y) plots the imaginary parts versus the real parts. Thus plot yin this case is equivalent to plot(real(y), imag(y)).
This situation is the only time when the plot function handles the imaginary parts in all other variants of the plot function, it ignore the imaginary parts.


Example:


Click to see image.




plot and fplot command:

MATLAB has a smart command for plotting functions. fplot analyzes the function to be plotted and decides how many plotting points to use so that the plot will show all the features of the function.


Syntax:


>> fplot (‘string’, [xmin xmax])

>> fplot (‘string’, [xmin xmax ymin ymax])

Example:


In this example we use this function cos(tan(x))-tan(sin(x)) to plot by using fplot and plot command.


With Plot: 


x=[0:0.1:10];

f = cos(tan(x))-tan(sin(x))
plot(x,f)



With fplot:


x=[0:0.1:10];

f = 'cos(tan(x))-tan(sin(x))'
fplot(f, [1 2])



Hold and figure command:


Hold command is used to create plot that needs two or more plots. Means we want to plot 2 or more graphs in the same window


Example:


x= [0:0.1:10];

y1=sin(x);
y2=cos(x);
plot(x,y1,'go')
hold
plot(x,y2,'r*', x,y2, ':')

legend('Sin(x)', 'Cos(x)')



Figure command is used to draw 2 or more graphs on different window as shown in example below.


Example:


x= [0:0.1:10];

y1=sin(x);
y2=cos(x);
figure
plot(x,y1,'go')
legend('Sin(x)')
hold on
figure
plot(x,y2,'r*', x,y2, ':')

legend('Cos(x)')



text and gtext command:


Text command is used to place the string text in the figure window at a point specified by coordinates x,y. 


Syntax:


>> text(x,y,’text’) 


Gtext command is used to place the string text in the Figure window at a point specified by the mouse. When you click the mouse on the window the text will appear there.


Syntax:


>> gtext(‘text’)


Example:


>> x= [0:0.1:10];

y1=cos(x);
y2=sin(x);
plot(x,y1,'go')
hold
plot(x,y2,'r*', x,y2, ':')
legend('cos(x)', 'sin(x)')
text(5,0,'plot of cos and sine')
gtext('This is the text to be
pasted by mouse')



Logarithmic Plots:

Why use log scales? 

Rectilinear scales cannot properly display variations over wide ranges.



A log-log plot can display wide variations in data values.




It is important to remember the following points when using log scales: 


1. You cannot plot negative numbers on a log scale, because the logarithm of a negative number is not defined as a real number. 


2. You cannot plot the number 0 on a log scale, because log10 0 = ln 0 = -infinity. You must choose an appropriately small number as the lower limit on the plot.


3. The tick-mark labels on a log scale are the actual values being plotted, they are not the logarithms of the numbers. For example, the range of x values in the plot in previous figure is from 10-1 = 0.1 to 102 = 100.

Syntax:

MATLAB has three commands for generating plots having log scales. The appropriate command depends on which axis must have a log scale.

1.Use the loglog(x,y) command to have both scales logarithmic. 


2. Use the semilogx(x,y) command to have the x scale logarithmic and the y scale rectilinear. 


3. Use the semilogy(x,y) command to have the y scale logarithmic and the x scale rectilinear.


Example:


x=0:0.5:50;

y=5*x.^2;
subplot(2,2,1), plot(x,y)
title('Polynomial - linear/linear')
ylabel('y'),grid
subplot(2,2,2), semilogx(x,y)
title('Polynomial - log/linear')
ylabel('y'),grid
subplot(2,2,3), semilogy(x,y)
title('Polynomial - linear/log')
ylabel('y'),grid
subplot(2,2,4), loglog(x,y)
title('Polynomial - log/log')
ylabel('y'),grid



Saving Figures in Matlab:


To save a figure that can be opened in subsequent MATLAB sessions, save it in a figure file with the .fig file name extension. To do this, select Save from the Figure window File menu or click the Save button (the disk icon) on the toolbar. If this is the first time you are saving the file, the Save As dialog box appears. Make sure that the type is MATLAB Figure (*.fig). Specify the name you want assigned to the figure file. Click OK.


Requirements for a Correct Plot:


The following list describes the essential features of any plot:


1. Each axis must be labeled with the name of the quantity being plotted and its units! If two or more quantities having different units are plotted (such as when plotting both speed and distance versus time), indicate the units in the axis label if there is room, or in the legend or labels for each curve.


2. Each axis should have regularly spaced tick marks at convenient intervals—not too sparse, but not too dense—with a spacing that is easy to interpret and interpolate. For example, use 0.1, 0.2, and so on, rather than 0.13, 0.26, and so on.



3. If you are plotting more than one curve or data set, label each on its plot or use a legend to distinguish them.

4. If you are preparing multiple plots of a similar type or if the axes’ labels cannot convey enough information, use a title.


5. If you are plotting measured data, plot each data point with a symbol such as a circle, square, or cross (use the same symbol for every point in the same data set). If there are many data points, plot them using the dot symbol.


6. Sometimes data symbols are connected by lines to help the viewer visualize the data.




Strings


>> In this tutorial we will discuss about the strings in MATLAB. Creating a character string is quite simple in MATLAB. In fact, we have used it many times. For example, you type the following in the command prompt as shown. Click on the picture to see.



MATLAB considers all variables as arrays, and strings are considered as character arrays. Let us use the whos command to check the variable created above:


Interestingly, you can use numeric conversion functions like uint8 or uint16 to convert the characters in the string to their numeric codes. The char function converts the integer vector back to characters:

Example:

Create a script file and type the following code into it:



my_string = 'Tutorial' 's Point';

str_ascii = uint8(my_string)        % 8-bit ascii values

str_back_to_char= char(str_ascii)  

str_16bit = uint16(my_string)       % 16-bit ascii values

str_back_to_char = char(str_16bit)

When you run the file, it displays the following result. Click on the picture to see.



Rectangular Character Array:



The strings we have discussed so far are one-dimensional character arrays; however, we need to store more than that. We need to store more dimensional textual data in our program. This is achieved by creating rectangular character arrays. Simplest way of creating a rectangular character array is by concatenating two or more one-dimensional character arrays, either vertically or horizontally as required. You can combine strings vertically in either of the following ways:



>> Using the MATLAB concatenation operator [ ] and separating each row with a semicolon (;). Please note that in this method each row must contain the same number of characters. For strings with different lengths, you should pad with space characters as needed.



>> Using the char function. If the strings are different length, char pads the shorter strings with trailing blanks so that each row has the same number of characters.

Example:

>> Create a script file and type the following code into it:

doc_profile = ['Zara Ali '; ...
               'Sr. Surgeon '; ...
               'R N Tagore Cardiology Research Center']
doc_profile = char('Zara Ali', 'Sr. Surgeon', ...
                   'RN Tagore Cardiology Research Center')

>> When you run the file, it displays the following result:

doc_profile =
Zara Ali                             
Sr. Surgeon                          
R N Tagore Cardiology Research Center
doc_profile =
Zara Ali                            
Sr. Surgeon                         
RN Tagore Cardiology Research Center

>> You can combine strings horizontally in either of the following ways:



1. Using the MATLAB concatenation operator, [ ] and separating the input strings with a comma or a space. This method preserves any trailing spaces in the input arrays.



2. Using the string concatenation function, strcat. This method removes trailing spaces in the inputs


Example:



>> Create a script file and type the following code into it:



name =     'Zara Ali ';

position = 'Sr. Surgeon '; 

worksAt =  'R N Tagore Cardiology Research Center';
profile = [name ', ' position ', ' worksAt]
profile = strcat(name, ', ', position, ', ', worksAt)

>> When you run the file, it displays the following result:

profile =
Zara Ali                             , Sr. Surgeon                          , R N Tagore Cardiology Research Center
profile =
Zara Ali,Sr. Surgeon,R N Tagore Cardiology Research Center

Combining Strings into a Cell Array:

From our previous discussion, it is clear that combining strings with different lengths could be a pain as all strings in the array has to be of the same length. We have used blank spaces at the end of strings to equalize their length. However, a more efficient way to combine the strings is to convert the resulting array into a cell array. MATLAB cell array can hold different sizes and types of data in an array. Cell arrays provide a more flexible way to store strings of varying length. 

The cellstr function converts a character array into a cell array of strings.

Example

>> Create a script file and type the following code into it:


name =     ' Zara Ali ';

position = ' Sr. Surgeon '; 
worksAt =  ' R N Tagore Cardiology Research Center ';
profile = char(name, position, worksAt) ;
profile = cellstr(profile) ;
disp(profile)

>> When you run the file, it displays the following result:


' Zara Ali '

' Sr. Surgeon '

' R N Tagore Cardiology Research Center '

String Functions in MATLAB

MATLAB provides numerous string functions creating, combining, parsing, comparing and manipulating strings. Following table provides brief description of the string functions in MATLAB. Click image to see.



Examples

The following examples illustrate some of the above-mentioned string functions:


FORMATTING STRINGS

>> Create a script file and type the following code into it:

A = pi*1000*ones(1,5);

sprintf(' %f \n %.2f \n %+.2f \n %12.2f \n %012.2f \n', A)

>> When you run the file, it displays the following result:


ans =

 3141.592654 
 3141.59 
 +3141.59 
      3141.59 
 000003141.59

JOINING STRINGS

>> Create a script file and type the following code into it:

%cell array of strings

str_array = {'red','blue','green', 'yellow', 'orange'};

% Join strings in cell array into single string

str1 = strjoin("-", str_array)
str2 = strjoin(",", str_array)

>> When you run the file, it displays the following result:


str1 =

red blue green yellow orange
str2 =
red , blue , green , yellow , orange

FINDING AND REPLACING STRINGS

>> Create a script file and type the following code into it:

students = {'Zara Ali', 'Neha Bhatnagar', ...

            'Monica Malik', 'Madhu Gautam', ...
            'Madhu Sharma', 'Bhawna Sharma',...
            'Nuha Ali', 'Reva Dutta', ...
            'Sunaina Ali', 'Sofia Kabir'};

% The strrep function searches and replaces sub-string.

new_student = strrep(students(8), 'Reva', 'Poulomi')
% Display first names
first_names = strtok(students)

>> When you run the file, it displays the following result:


new_student = 

    'Poulomi Dutta'
first_names = 
  Columns 1 through 6
    'Zara'    'Neha'    'Monica'    'Madhu'    'Madhu'    'Bhawna'
  Columns 7 through 10
    'Nuha'    'Reva'    'Sunaina'    'Sofia'

COMPARING STRINGS

>> Create a script file and type the following code into it:

str1 = 'This is test'

str2 = 'This is text'
if (strcmp(str1, str2))
 sprintf('%s and %s are equal', str1, str2)
else
 sprintf('%s and %s are not equal', str1, str2)
end

>> When you run the file, it displays the following result:


str1 =

This is test
str2 =
This is text
ans =

This is test and This is text are not equal

Colon notation


>> The colon( : ) is one of the most useful operator in MATLAB. It is used to create vectors, subscript arrays, and specify for iterations. If you want to create a row vector, containing integers from 1 to 10, you write:




If you want to specify an increment value other than one, for example:




You can use the colon operator to create a vector of indices to select rows, columns or elements of arrays.


Try this example yourself:



0:pi/8:pi

ans = .........?


The following picture describes its use for this purpose (let us we have a matrix A):




Example:





Arrays operation


1. Array Addition and Subtraction:


For example




Array subtraction is performed in a similar way. The addition shown in above equation is performed in MATLAB as follows:




2. Array multiplication:


Multiplying a matrix A by a scalar w produces a matrix whose elements are the elements of A multiplied by w. For example:




This multiplication is performed in MATLAB as follows:




Multiplication of an array by a scalar is easily defined and easily carried out. However, multiplication of two arrays is not so straightforward. 


MATLAB uses two definitions of multiplication:


a. array multiplication (also called element-by-element multiplication)



b. matrix multiplication.

MATLAB has two forms of arithmetic operations on arrays. One form, called array operations, which are also called element-by-element operations. And matrix operations. Each form has its own applications.



Division and exponentiation must also be carefully defined when you are dealing with operations between two arrays.




Array or Element-by-element multiplication is defined only for arrays having the same size. The definition of the product x.*y, where x and y each have n elements, is 

x.*y = [x(1)y(1), x(2)y(2), ... , x(n)y(n)] 
if x and y are row vectors. 

For example, 




If x and y are column vectors, the result of x.*y is a column vector. For example z = (x').*(y') gives 




Note that x' is a column vector with size 3 × 1 and thus does not have the same size as y, whose size is 1 × 3. Thus for the vectors x and y the operations x'.*y and y.*x' are not defined in MATLAB and will generate an error message.


The array operations are performed between the elements in corresponding locations in the arrays. For example, the array multiplication operation A.*B results in a matrix C that has the same size as A and B and has the elements ci j = ai j bi j . For example,




The built-in MATLAB functions such as sqrt(x) and exp(x) automatically operate on array arguments to produce an array result the same size as the array argument x.

Thus these functions are said to be vectorized functions.

For example, in the following session the result y has the same size as the argument x.



However, when multiplying or dividing these functions, or when raising them to a power, you must use element-by-element operations if the arguments are arrays.

For example, to compute 
z = (ey sin x) cos2x, 
you must type
z = exp(y).*sin(x).*(cos(x)).^2.

You will get an error message if the size of x is not the same as the size of y. The result z will have the same size as x and y.


3. Array division:


The definition of array division is similar to the definition of array multiplication except that the elements of one array are divided by the elements of the other array. Both arrays must have the same size. The symbol for array right division is ./ 

For example, if

x = [8, 12, 15] y = [–2, 6, 5]


then z = x./y gives



z = [8/(–2), 12/6, 15/5] = [–4, 2, 3]



4. Array exponentiation:


MATLAB enables us not only to raise arrays to powers but also to raise scalars and arrays to array powers. To perform exponentiation on an element-by-element basis, we must use the ( .^ ) symbol. For example, 

if x = [3, 5, 8], then typing x.^3 produces the array [33, 53, 83] = [27, 125, 512].

We can raise a scalar to an array power. For example, 

if p = [2, 4, 5], then typing 3.^p produces the array [32, 34, 35] = [9, 81, 243].


Remember that ( .^ ) is a single symbol. The dot in 3.^p is not a decimal point associated with the number 3. The following operations, with the value of p given here, are equivalent and give the correct answer:


>> 3.^p


>> 3.0.^p


>> 3..^p


>> (3).^p


>> 3.^[2,4,5]




Arrays


>> So far we almost cover all the major things to understan MATLAB. In this section we will learn about arrays. We already discussed vectors and matrices. In MATLAB, all variables of all data types are multidimensional arrays. A vector is a one-dimensional array and a matrix is a two-dimensional array. we will discuss multidimensional arrays. However, before that, let us discuss some special types of arrays.


Special Arrays in MATLAB:


In this section, we will discuss some functions that create some special arrays. For all these functions, a single argument creates a square array, double arguments create rectangular array.


>> zeros() = The zeros() function creates an array of all zeros.


Sometimes we want to initialize a matrix to have all zero elements. The zeros command creates a matrix of all zeros. Typing zeros(n) creates an n × n matrix of zeros, whereas typing zeros(m,n) creates an m × n matrix of zeros. For example:




>> ones() = The ones() function creates an array of all ones.


The syntax of the ones command is the same, except that it creates arrays filled with ones. For example:




>> eye() = The eye() function creates an identity matrix.


The functions eye(n) and eye(size(A)) create an n × n identity matrix and an identity matrix the same size as the matrix A. For example:




>> rand() = The rand() function creates an array of uniformly distributed random numbers on (0,1). For example:




>>  A magic square is a square that produces the same sum, when its elements are added row-wise, column-wise or diagonally.


magic() = The magic() function creates a magic square array. It takes a singular argument that gives the size of the square. The argument must be a scalar greater than or equal to 3. For example:




Multidimensional Arrays:


An array having more than two dimensions is called a multidimensional array in MATLAB. Multidimensional arrays in MATLAB are an extension of the normal two-dimensional matrix. Generally to generate a multidimensional array, we first create a two-dimensional array and extend it. For example, let's create a two-dimensional array a.



The array a is a 3-by-3 array; we can add a third dimension to a, by providing the values like:



We can also create multidimensional arrays using the ones(), zeros() or the rand() functions. For example,




We can also use the cat() function to build multidimensional arrays. It concatenates a list of arrays along a specified dimension:



Syntax for the cat() function is: B = cat(dim, A1, A2...)
Where,

a. B is the new array created.


b. A1, A2, ... are the arrays to be concatenated.



c. dim is the dimension along which to concatenate the arrays.

for example:




Array Functions:


MATLAB provides the following functions to sort, rotate, permute, reshape, or shift array contents.




Examples:


The following examples illustrate some of the functions mentioned above. 


>> Length, Dimension and Number of elements:




>> Circular Shifting the Array Elements:




Sorting Arrays:


This is used to sort the arrays for example,




Cell Array:


Cell arrays are arrays of indexed cells where each cell can store an array of a different dimension and data type.


The cell function is used for creating a cell array. Syntax for the cell function is:


C = cell(dim)

C = cell(dim1,...,dimN)
D = cell(obj)
Where,

a. C is the cell array;


b. dim is a scalar integer or vector of integers that specifies the dimensions of cell array C;


c. dim1, ... , dimN are scalar integers that specify the dimensions of C;


d. obj is One of the following:  >> Java array or object  >> .NET array of type System.String or System.Object


Example:




Accessing Data in Cell Arrays:


There are two ways to refer to the elements of a cell array:


a. Enclosing the indices in first bracket (), to refer to sets of cells


b. Enclosing the indices in braces {}, to refer to the data within individual cells


When you enclose the indices in first bracket, it refers to the set of cells. Cell array indices in smooth parentheses refer to sets of cells. For example:




You can also access the contents of cells by indexing with curly braces. For example: