Tutorial
Introduction to MatLab®
Overview
In this tutorial, we are going to learn the basic commands in MatLab.
Objectives
At the end of this Lab students will be able to:
a) use the MatLab GUI to enter commands
b) create and manipulate simple matrix
c) save to and read from text file
d) use the loops and conditional command
e) write MatLab script including function
Assumption: Students have some prior knowledge on C/C++ syntaxes and foundation on matrix and
its operations.
1. Introduction
MATLAB is a numerical computing environment and programming language. It contains a set of
core MatLab commands aided by powerful toolboxes. The toolbox provides a specialized set of tools
for various purposes. In this course we are going to learn the Fuzzy Logic, Neuro Fuzzy and Neural
Network Toolbox.
MATLAB is also the most powerful graphic tool. It can be used to plot 2D and 3D graphs through
command line.
2. MatLab GUI
Workspace
Current window
folder
window
Command window
Command
history
window
The Command Window
You will be using the command window most of the time in the labs. The command window allows
you to enter commands through the command prompt >>.
Once a command in entered simply press the enter key to execute it. The output will appear
immediately after the execution (only in the case where no semicolon is used to terminate the
command).
Working Directory
The working directory window shows the current directory you are working on. User defined
variables or script files are usually stored in organized directories. So if you would like to access
these items you have to change your current working directory into the directory that stored it. To
change current working directory, simply click on the browse directory button on the main toolbar.
Throughout the labs we will ask students to store downloaded files into certain directory to work with.
So, it is recommended you create one folder to store all your files so that you can reuse it in
subsequent labs. Once you have created your folder you can change the matlab current working
directory to that folder.
Workspace Window
The workspace window allows you to view list of variables currently available in the Matlab. They are
usually user defined variables. You can also use the workspace window to manually create variables.
Retrieving Old Commands
Like DOS command prompt, you can retrieve the commands you have entered using the up or down
arrow key. This is convenient because you do not need to retype the same commands.
3. Variables
o In MatLab, variables are not required to be declared prior to using it. Variables will be
automatically created when you first use it.
o Variables can be created in the workspace by simply entering the variable name. Variable
names are case sensitive.
o All variables are treated as matrix in MatLab.
o Variables data types are automatically assigned when you first assign value to it. The data
type for an existing variable will change when you assign a different data type value to it.
o Standard data types supported by MatLab are:
Integer
Real
String
Character
Examples:
>>a = 5 %integer
a=
5
>>b = 5.25 %real
b=
5.2500
>>c='hello' %string: array of characters
c=
hello
>>d='a' %character
d=
a
Note that: % is a comment. You can see the variables you created will be listed in the
Workspace window.
o When you perform MatLab operations and the result is not assigned to any variable, it will be
automatically assigned to a global variable named ans. You can access this variable from
anywhere in MatLab.
E.g.:
>>2+5
ans=
7
o To view global variables you have created in the Command window just type whos.
o MatLab also provide three variables representing non numbers:
-inf Negative infinity Use to represent value overflow or
division by 0
Inf Positive Infinity
NaN Not-a-Number Use to represent mathematical
undefined operation such as 0.0/0.0
4. Using Help
MatLab provides a nice help system to allow you to search for documentation regarding its
commands and functions.
help command
The help command can be used to understand the functions of MatLab built in or user defined
functions. For example, in the command window type,
>>help sqrt
SQRT Square root.
SQRT(X) is the square root of the elements of X. Complex results are produced if X is not positive.
See also SQRTM.
lookfor command
If you do not remember a function name exactly, lookfor will help to search for a function by only
specifying its partial name.
E.g.:
>>lookfor mean
will returns all function names that include 'mean'.
online help
MatLab offer complete online documentations for all functions and features provided. To learn more,
just visit http://www.mathworks.com/help/matlab/index.html
5. Creating Matrix and Matrix Properties
In MatLab, matrix/vector entries are enclosed by the bracket "[ ]".
Creating column vectors
>>a = [5; 7; 10]
The symbol ; is the row separator.
Creating a 1x3 row vectors
>>b=[4 5 10] or >>b=[4, 5, 10]
Creating a 3x3 matrix
>>c=[1 5 4; 6 10 12; 7 25 2]
Note: One often does not want to see the result of intermediate calculations, in this case, you can
terminate the assignment statement or expression with semi-colon ;.
Exercise:
Create the following matrix:
1 3 4
5.1 2.5 2
d
5 4 4
45 12 5
o Creating a matrix automatically
Often you would like to create matrix used to store values later. MatLab provides three
functions for this purpose.
a) zeros([m, n]) - this function returns a square matrix with size nxn. All entries are filled with 0.
Whereas zeros(m, n) or zeros([m, n]) creates a mxn matrix filled with 0.
>> zeros(3)
ans =
000
000
000
b) zeros(3,2)
>> zeros(3,2)
ans =
00
00
00
c) eye function creates an identity matrix.
>> eye(3)
ans =
100
010
001
eye(M,N) or eye([M,N]) is a M-by-N matrix with 1's on the diagonal and zeros elsewhere.
d) ones function generates a matrix filled with 1.
>> ones(2,3)
ans =
111
111
ones(N) generates a NxN square matrix.
e) An empty matrix
An empty matrix can be created by simply entering:
>> d=[]
Note: you can check if a matrix is empty by using the built in function isempty().
f) To generate a random matrix you can use the rand() function..
To generate uniform random numbers with minimum and maximum bounds other than 0 and 1
respectively, use the following formula:
E.g.:
>>R = rand(3,4);
>>x = ((b-a) * R) + a;
with "R" being the random variable, "b" representing the upper bound and "a" representing the lower
bound.
g) Creating a matrix by combining existing matrix or matrices. For example:
>> B=[1 2; 3 4];
>> C=[5 6; 7 8];
>> D=[B C]
D=
1256
3478
Often we would like to know the properties of a matrix. Two useful functions are size() and length().
The size function returns the dimension of a matrix as row vector.
e.g. [M N] = size(A); where M is the number of rows and N is the columns for matrix A respectively.
The length function returns the larger of the two dimensions of a matrix.
6. Viewing, Saving and Retrieving Saved Variables
It is importance to know the current working directory. This directory will by default use to save the
variables and script files. To check for current working directory type pwd. Alternatively, you can
check the current directory in the Current Folder window. The Current Folder window can be
displayed or hide by going to Window menu and check/uncheck the Current Folder sub-menu.
To view variables you have created in the Workspace, simply type whos (to view a specific variable,
type who variable).
To delete all existing variables in the workspace, type clear.
Matlab allows you to save variables defined in the workspace (as .mat file) to be retrieved later. To
save all current variables, type save filename in the command window. Alternatively, you can go to
File menu and choose Save Workspace As... You can load the saved variables by using the
command load filename. The content of the file by default is binary with .mat extension. You can
specify an optional parameter - ASCII if you would like to save the variables as text file. For example,
save filename -ASCII
If you would like to save only some of the variables in the current workspace, the syntax is save
filename var1 var2 ; where var1 and var2 are variables to save.
To load saved variables, type load filename.
If you would like to preview variables saved into a .mat file you can type:
whos -file filename
Exercise:
Use whos to list all variables define in your workspace.
Save all variables into a file named myvariable.
Save any one of the variables into a file named onevariable.
Now, clear the workspace using the clear command.
Reload the variable saved in onevariable.mat file. Type the whos command to check if it
has been loaded.
7. Accessing Matrix Elements
MatLab offers a number of options to access matrix entries.
To access a single matrix entry use the subscript operator (). E.g.:
>> D
D=
1256
3478
>> D(1, 2) %access the first row and 2nd column
ans =
>> D(2,3) %access the 2nd row and third column
ans =
7
Note that, in MatLab the matrix row and column index begins with 1.
o The Colon notation
The colon notation : is very useful in MatLab as we will see soon.
The colon : is used to define vectors that can act as subscripts. For integers i and j, i:j denotes the
row vector of integers from i to j (with the step of 1). We can also specify the step size by using the
syntax i:s:j. i, j and s could be a real or integer value. However, to access matrix entries only
positive integer value can be used.
Example:
>> 1:5
ans =
12345
>> -10:3:5
ans =
-10 -7 -4 -1 2 5
To access a range of values in a matrix we can use the colon notation to generate the matrix
subscripts.
Example:
r=
1 3 5 -1 -3 -5 -7
>> r(2:5)
ans =
3 5 -1 -3
>> r(1:2:6)
ans =
1 5 -3
To extract a submatrix from a matrix A, the syntax is A(p:q,r:s), where p to q are the rows and r to s
are the columns of the matrix to extract.
A=
235
7 11 13
17 19 23
>> A(1:3, 1:2) % extracting submatrix rows 1 to 3 and columns 1 to 2.
ans =
23
7 11
17 19
>> A(1:2,2:3) %extracting submatrix rows 1 to 2 and columns 2 to 3.
ans =
35
11 13
o The keyword end can be used as index for the last column or row of a matrix. For example:
>> A = rand(4, 3)
A=
0.9318 0.5252 0.0196
0.4660 0.2026 0.6813
0.4186 0.6721 0.3795
0.8462 0.8381 0.8318
>>A(1,end)
ans =
0.0196
>> A(end, 2)
ans =
0.8381
>> A(2:end, 2:end)
ans =
0.2026 0.6813
0.6721 0.3795
0.8381 0.8318
o The colon notation can be used to extract the whole column or row of a matrix.
For example: A(:, 1) returns the 1st column from matrix A.
A(2, : ) returns the second row from matrix A.
This is very convenience if you would like to extract certain row or column from a matrix for further
processing.
A=
0.9318 0.5252 0.0196
0.4660 0.2026 0.6813
0.4186 0.6721 0.3795
0.8462 0.8381 0.8318
>> A(:, 2)
ans =
0.5252
0.2026
0.6721
0.8381
>> A(3, :)
ans =
0.4186 0.6721 0.3795
8. Matrix Arithmetic, Matrix Operations and Analysis
All standard matrix operations are supported by MatLab. These include matrix multiplication and
addition, matrix entry wise addition, division, and multiplication. We will also learn some basic matrix
operations.
Matrix Operation Command
Inverse A-1 inv(A)
Transpose A' transpose(A) or A'
Example:
>> A=rand(2)
A=
0.4218 0.7922
0.9157 0.9595
>> A'
ans =
0.4218 0.9157
0.7922 0.9595
>> inv(A)
ans =
-2.9912 2.4697
2.8548 -1.3148
o Delete a row or a column of a matrix
To delete a row or column of a matrix, you simply assign an empty matrix [] to the row or column.
>> B=rand(3)
B=
0.8600 0.4966 0.6449
0.8537 0.8998 0.8180
0.5936 0.8216 0.6602
>> B(:, 1) = []
B=
0.4966 0.6449
0.8998 0.8180
0.8216 0.6602
>> B(2, :) = []
B=
0.4966 0.6449
0.8216 0.6602
Find out what will the following operation produce?
B([1 2], :). Can we use this operation to delete column(s)/row(s)?
MatLab support matrix and entry wise operations.
Operation Matrix sense Array sense
Addition + +
Substraction - -
Multiplication * .*
Left division / (\) ./ (.\)
Exponentiation ^ .^
Let A and B be matrices, then A*B is the matrix multiplication and A .* B is entry wise multiplication.
A^2 is equivalent to A*A.
A/B is a solution for A*B-1.
A\B is a solution for A-1*B.
Example:
>>A
A=
12
34
>> B
B=
11
11
>> A*B
ans =
33
77
>> A .*B
ans =
12
34
o Min and Max function
If X is a vector, min and max returns the minimum and maximum value in X respectively. sum
returns the sum of elements in vector X. If Y is a matrix, sum returns a row vector with each element
represent the sum of each column vector in Y. min/max will returns the minimum/maximum value at
each column of Y.
>> X = [4 -8 -1 1 0];
>> [min(X) max(X)]
ans =
-8 4
>> sum(X)
ans =
-4
>> Y = [4 5 3; 1 2 3];
>> sum(Y)
ans =
576
If Y is a matrix, what will the following command return min(min(Y))?
Exercises
i) Create a matrix called A with the following entries.
5 5 321 94 1
49 21 25 2 56
8 7 89 3 83
ii) Access all values in the second row of the matrix A.
iii) Append the following row vector into the matrix A as the last row.
20 9 5 89 100
iv) Delete the third column of the matrix A.
v) Continuing from the previous step, find the maximum, minimum and sum of the matrix A.
9. Input and Output
o User input
User input can be obtained with the input function.
E.g.:
>>x = input('Please enter a positive integer:')
Please enter a positive integer: 2
x=
To read a string, you can include the parameter as part of input function argument.
E.g.:
>>name = input('Please enter your name:', 's')
To pause the execution of command until a key is pressed, use the pause command. You can find
out more about pause through the MatLab help system.
o Output to screen
The results of MatLab computations are displayed on the screen whenever a semicolon is omitted
after an assignment and the format of the output can be varied using the format command.
However, it is not flexible enough for most purposes. MatLab provides a number of powerful
functions. In this lab we are going to learn the disp and fprintf functions.
disp function
E.g.:
>> disp('This is a text');
This is a text
>> disp(rand(3));
0.9501 0.4860 0.4565
0.2311 0.8913 0.0185
0.6068 0.7621 0.8214
>> C=2;
>> D=3;
>> disp(C), disp('+'), disp(D), disp('='), disp(C+D);
2
+
3
=
5
fprintf function
fprintf function works quite similar to C/C++ printf function.
The syntax is : fprintf(format, list-of-expressions)
where format is a string that specifies the precise output format for each expression in the list. list-of-
expressions are expressions that evaluated to certain values.
Example:
>>fprintf('%6.3f\n', pi)
3.142
In this example, % is the start of a formatter specifier, 6.3 means requesting a field width of 6 with 3
digits after the decimal point, and f is the real type formatter.
Example:
>>A=4.53;
>> fprintf('The square root of %.2f is %.3f\n', A, sqrt(A));
The square root of 4.53 is 2.128
Other C/C++ type formatters are supported. You can refer to C/C++ manual to get more information.
Check out the sprintf function using MatLab help system.
o Saving data
In our lab practices we will mostly deal with tabular text file format. In tabular text file, each row
represents an input pattern from a fixed number of variables. Each value of a variable is separated
by a delimiter. The delimiters could be space, tab or comma. If it is delimited by a comma, then we
called it a .csv file which can be opened using Microsoft Excel. In fact all text files can be imported
into Excel by using its import wizard.
An example of comma delimited file.
11, 0.5, 45, 205, 0.25
51, 0.25, 252, 20, 0.1
....
In this example, there are five variables.
a) save command
In Section 6, we have seen how to save variables into text file using the ASCII option. NOTE that the
save command cannot only be used to save string variables into an ASCII file. However, saving
into .mat file is fine. The save command can be used if you would like to save numerical data for one
single variable where the data values are delimited by a tab or space.
For example:
To export the array A, A = [ 1 2 3 4 ; 5 6 7 8 ];
use the save function, as follows:
save my_data.out A -ASCII
If you view the created file in a text editor, it looks like this:
1.0000000e+000 2.0000000e+000
3.0000000e+000 4.0000000e+000
5.0000000e+000 6.0000000e+000
7.0000000e+000 8.0000000e+000
By default, save uses spaces as delimiters but you can use tabs instead of spaces by specifying the
- tabs option.
b) csvwrite command
csvwrite(filename,M) writes matrix M into filename as comma-separated values. The filename input
is a string enclosed in single quotes.
Try the following example:
Creates the following matrix:
>>m = [3 6 9 12 15; 5 10 15 20 25; 5 10 15 20 25; 7 14 21 28 35; 7 14 21 28 35; 11 22 33 44 55];
>>csvwrite('csvlist.dat', m);
To view the file content, enter >> type csvlist.dat.
o Reading a text file
a) load command
The load function can be used to retrieve variables from the .mat file. It also can be used to read text
file that contain rows of delimited values. For example,
25 0.5 0.35 255
30 1.5 0.11 300
...
load function can only be used to read numerical values. To use load to read a text, the syntax
is:
variable=load( filename)
where filename is a string value. After successfully loading a text file, the assigned variable will hold
all the data values as a matrix.
If the file extension is other than .mat, it is assumed to be an ASCII file. Section 6 discussed how to
use load to read a .mat file.
b) csvread command
csvread read the comma separated values file (note that only numerical values can be read). The
syntax is,
variable=csvread(filename)
Example:
Using the csv file you have saved previously, enter B=csvread('csvlist.dat'). Then display matrix B
values.
10. MatLab Scripts
M-files (.m) are files where you write your MatLab programming language. Through m-file you can
write useful codes and functions to do some data processing. MatLab provided a M-file editor for you
to type the codes. To create an M-file, click on [File->New->M-file]. Once you have created an M-file
(.m) you can execute it by simply typing it file name. Note that, the M-file must be in one of the
directories in the MatLab search path or in the current working directory.
The M-file can be saved into any directory. However, it is usually saved into the current matlab
working directory so that matlab can locate it during execution. To execute a m-file you simply type
the file name (without the .m). For example, to execute a script file named test.m, you type test in
the command line. For function script file (see below), you might require to supply some input
parameters.
A script enables you to store a sequence of commands that are to be used repeatedly or will be
needed at some future time.
o Script M-files
A script file has no input or output arguments and operate on variables in the workspace. It simply
consists of MatLab commands.
o Function M-files
Is a script file that contains a function definition line and can accept input arguments and return
output arguments, and their internal variables are local to the function.
Example:
The area, A, of a triangle with sides of length a, b and c is given by
A s( s a )(s b)(s c)
where s = (a + b + c)/2. Write a MatLab function that will accept the values a, b and c as inputs and
return the value of A as output.
The main steps to follow when defining a MatLab function are:
a) Decide on a name for the function, making sure that it does not conflict with a name that is
already used by MatLab. In this example, the name of the function is to be area, so its
definition will be saved in file called area.m
b) The first line of the file must have the format:
function [list of outputs] = function name(list of inputs)
For our example, the output (A) is a function of the three variables (inputs) a, b and c so the
first line should read function [A] = area(a,b,c)
NOTE!!! Unlike most programming languages, there is no need to specify the data type for
the input arguments in the function.
c) Document the function. That is, describe briefly the purpose of the function and how it can be
used. These lines should be preceded by % which signifies that they are comment lines that
will be ignored when the function is evaluated. [This step is however, optional]
d) Finally include the code that defines the function. This should be interspersed with sufficient
comments to enable another user to understand the processes involved. The complete file
might look like:
function [A] = area(a,b,c)
% Compute the area of a triangle whose sides have length a, b and c.
% Inputs:
% a,b,c: Lengths of sides
% Output:
% A: area of triangle
% Usage:
% Area = area(2,3,4);
s = (a+b+c)/2;
A = sqrt(s*(s-a)*(s-b)*(s-c)); %function return
%%%%%%%%% end of area %%%%%%%%%%%
To evaluate the area of a triangle with side of length 10, 15, 20:
>> Area = area(10,15,20)
Area =
72.6184
If we were to be interested in the value of s as well as A, then the first line of the file should be
changed to function [A, s] = area(a,b,c) where there are two output variables.
This function can be called in several different ways:
1. No outputs assigned
>> area(10,15,20)
ans =
72.6184
gives only the area (first of the output variables from the file) assigned to ans; the second output is
ignored.
2. One output assigned
>> Area = area(10,15,20)
Area =
72.6184
again the second output is ignored.
3. Two outputs assigned
>> [Area, hlen] = area(10,15,20)
Area =
72.6184
hlen =
22.5000
The return command causes a return to the invoking function or to the keyboard. It is a good
practice to name the m-file as the function name.
o Logical and relational operators
MatLab support all logical and relational operators available in C/C++.
Relational operator C/C++ MatLab
equal == == or eq()
not equal != ~= or ne()
less than < < or lt()
greater than > > or gt()
less than or equal <= <= or le()
greater than or equal >= >= or ge()
Note that: 5 > 7 is equivalent to gt(5, 7) and etc.
These relational operators can also be used to compare matrices or vectors with the same
dimension.
Logical operator C/C++ MatLab
AND && &
OR || |
NOT ! ~
>>A=[1 2; 3 4]; >> A=[-1 1 1]; B=[1 2 -3];
>> B=[-1 2; 6 7]; >> A>0 & B>0
>> A == B
ans =
ans =
010
01
00 >> A>0 | B>0
>>A > 2 ans =
ans =
00 111
11
o Conditional statement
MatLab also support C/C++ like conditional statements such as IF-ELSE and SWITCH.
IF-ELSE
Syntax:
if expression
statements
end
E.g.:
if x > y
temp = y;
y=x;
x=temp;
end
Note there are several differences between MatLab and C/C++ if-else statements.
in MatLab no opening and closing curly bracket is (i.e. {}) needed for the if statements.
In MatLab, statements are ended with an end command.
in MatLab, it is optional to use the round bracket () for the expression.
Alternatives
if expression1
statements
elseif expression2
statements
end
E.g.:
if a > 1 & a < 5
calc = 5.0 * A;
elseif a > 5 & a < 10
calc=2.53 * A;
else
calc=25 * A;
end
SWITCH statement
E.g.:
for i=1:4
switch i;
case {1}
disp('i is one');
case {2}
disp('i is two');
case {3}
disp('i is three');
otherwise
disp('i is not one, two, or three');
end
end
FOR loop
Syntax:
for variable=expression
statements
end
where expression is usually in the form i:s:j; i is the start value, j is the end value an s is the
incremental step size.
E.g.:
for w=1:2:10
fprintf('%d\t', w);
end
display 1 3 5 7 9
WHILE loop
while expression
statements
end
error = 283.4;
tol = 1;
factor = 0.9;
while (error > tol)
error = factor*error;
fprintf('error = %.2f\n', error);
end
ans:
error = 255.06
error = 229.55
error = 206.60
.
.
.
error = 1.18
error = 1.06
error = 0.96
break and continue command
These two commands, which use in loop statements, perform similar functions as in C/C++.
Exercises
1. Type in the command that will load the ASCII numerically data stored in Data.txt into a
variable called stuff. Saves the data stored in the variable stuff into a csv file called
stuff.csv.
2. The Marks.txt file contains student's ids and their marks for two subjects. Load the
Marks.txt into an appropriate variable. Find the grade for each subject for all the students
according to the following grading:
Marks Grade
<50 F
50-55 D
55-65 C
65-80 B
80-100 A
Display on Matlab command window the grades and average marks of each student and
saves all information into a csv file by assuming grade A is represented by an integer value 1,
B is value 2, C is value 3…etc. Note that you can append a column vector into existing
vector/matrix using the following command.
a=[a b]
where b is a new column vector (nx1), a is a matrix with size (nxm). For this task it is better to
enter the commands into a script file.
2D Plot
% The basic command for making a 2-D plot is "plot". The following code makes a plot of the
% function sin(x).
x = linspace(0,2*pi,200);
f1 = sin(x);
plot(x,f1)
% we now add a title and labels for the x and y axes
title('Plot of f_1 = sin(x)');
xlabel('x');
ylabel('f_1');
% Let us change the axes so that they only plot x from 0 to 2*pi.
axis([0 2*pi -1.1 1.1]); %[xmin xmax ymin ymax]
% Next, we make a new figure with cos(x)
f2 = cos(x);
figure; % makes a new figure window
plot(x,f2);
title('Plot of f_2 = cos(x)');
xlabel('x');
ylabel('f_2');
axis([0 2*pi -1.1 1.1]);
% Now, we make a single graph with both plots
figure; % creates a new graph
plot(x,f1);
hold on; % tells MATLAB not to overwrite current plot
% What happens if you forget to type hold on? "hold off" removes the hold.
plot(x,f2,'r'); % plots with red curve
title('Plots of f_1 = sin(x), f_2 = cos(x)');
xlabel('x');
ylabel('f_1, f_2');
axis([0 2*pi -1.1 1.1]);
%Now we add a legend.
legend('f_1', 'f_2');
%If we want to move the legend, we can go to the "Tools" menu of the figure window and turn on
%"enable plot editing" and then drag the legend to where we want it.
%Finally, we use the command "gtext" to add a line of text that we then position on the graph using
%our cursor.
gtext('add a line of text on the graph');
gtext('add a second line of text on the graph');
%The command "help plot" tells how to make a graph using various types of points instead of lines
% and how to select different colors.
clear all
3-D plot
%3-D plots
%First, we generate a grid containing the x and y values of each point.
x = 0:0.2:2*pi; %create vector of points on x-axis
y = 0:0.2:2*pi; %create vector of points on y-axis
%Now if n=length(x) and m=length(y), the grid will contain N=n*m grid points. XX and YY are n by m
%matrices containing the x and y values for each grid point respectively.
[XX,YY] = meshgrid(x,y);
%The convention in numbering the points is apparent from the following lines.
x2 = 1:5; y2 = 11:15;
[XX2,YY2] = meshgrid(x2,y2);
XX2, YY2
%This shows that XX2(i,j) contains the jth component of the x vector and YY2(i,j) contains the
%ith component of the y vector.
%Now, we generate a function to save as a separate z-axis value for each (x,y) 2-D grid point.
Z1 = sin(XX).*sin(YY); %calculate value of function to be plotted
%create a colored mesh plot
figure; mesh(XX,YY,Z1);
xlabel('x'); ylabel('y'); zlabel('z'); title('sin(x)*sin(y)');
%create a colored surface plot
figure; surf(XX,YY,Z1);
xlabel('x'); ylabel('y'); zlabel('z'); title('sin(x)*sin(y)');
%create a contour plot
figure; contour(XX,YY,Z1);
xlabel('x'); ylabel('y'); zlabel('z'); title('sin(x)*sin(y)');
%create a filled contour plot with bar to show function values
figure; contourf(XX,YY,Z1); colorbar;
xlabel('x'); ylabel('y'); zlabel('z'); title('sin(x)*sin(y)');
%create a 3-D contour plot
figure; contour3(XX,YY,Z1);
xlabel('x'); ylabel('y'); zlabel('z'); title('sin(x)*sin(y)');
clear all