INTRODUCTION TO MATLAB
You should start MATLAB by simply typing matlab if you are working on a Unix system or just by double clicking the MATLAB icon if you are using a Windows based system. If all goes well you will see a MATLAB prompt
inviting you to initiate a calculation. In what follows, any line beginning with >> indicates typed input to MATLAB. You are expected to type what follows by not the >> prompt itself. MATLAB supplies that automatically.
Arithmetic with MATLAB
MATLAB understands the basic arithmetic operations: +, -, *, /. Powers are indicated with ^, thus typing
>> 5*4 + 3^2
and pressing enter, results in
The laws of precedence are built in but if in doubt, you should put parentheses appropriately. For example,
The sort of elementary functions familiar on hand calculators are also available. For example,
You can assign numerical values to variables for use in subsequent calculations. For example the volume of a sphere can be calculated via the following sequence:
>> radius = 3;
Note that the first line did not seem to produce a result in screen. When MATLAB encounters an instruction followed by a semi-colon ; it suppresses any visual confirmation. It really does obey the instruction and records the value of the variable in the memory. This is useful if you want to avoid cluttering up the screen with intermediate results. Each variable must somehow be assigned before you make use of it in further calculations. For example if you have followed the above example with,
you should get the result,
??? Undefined function or variable ‘h’
This is self-explanatory. If you now type
you should have more success. Incidentally, a quick way of repeating a previous MATLAB instruction is to press the ‘up-arrow’ key until you recover the command you need. You may also use the sideways arrows to modify any of the previous commands.
At any point typing the command,
tells about all the variables that are in the workspace of the current MATLAB session.
A vector can be input in several ways. For example,
>> u=[fusion_builder_container hundred_percent=”yes” overflow=”visible”][fusion_builder_row][fusion_builder_column type=”1_1″ background_position=”left top” background_color=”” border_size=”” border_color=”” border_style=”solid” spacing=”yes” background_image=”” background_repeat=”no-repeat” padding=”” margin_top=”0px” margin_bottom=”0px” class=”” id=”” animation_type=”” animation_speed=”0.3″ animation_direction=”left” hide_on_mobile=”no” center_content=”no” min_height=”none”][1 3 5];
All three commands above yield the same vector. One can perform vector operations such as,
Note that the vectors described so far are row vectors. To get a corresponding column vector, we invoke the transpose of a vector. For example,
The difference between the vectors u and u’ can be understood by typing the commands
which yields the row size followed by the column size for each vector. One can now multiply vectors appropriately to either yield an innerproduct
or a matrix,
Multiplication of vectors only happens if the inner matrix dimensions agree. For example,
??? Error using ==> *
Inner matrix dimensions must agree.
Suppose we want a set of values z given by z = u2 then we want
>> z = u.*u;
where the . is inserted before the * symbol which forces an element-by-element operation. Similarly u./v and u.^3 can be understood to be the corresponding element-by-element operations.
Example: Suppose we want to find the distance between two points A and B whose position vectors are given by a = (1, 2) and b = (5, 5) respectively. The following sequence of commands can be executed in MATLAB to obtain the desired result:
>> a=[1 2];
>> b=[5 5];
>> d = b – a;
>> dd = d*d’;
>> dist_ab = sqrt(dd)
Now suppose we want to modify the position vectors and find the distance between the new coordinates, it will not be worthwhile to type all the commands again. Instead one can create a script file, which will contain all the necessary information. To create a new script file, one can open their favorite text editor and type the following commands,
% Calculates distance between any two position vectors a and b
Save these contents in a file named dist_ab.m and note that the script file has a ‘.m’ extension which denotes that it is a MATLAB file. Now one can pick values for the vectors a and b by simply typing say,
>> a=[1 2 3];
>> b=[5 5 3];
Then find the distance by simply typing
This program can be called repeatedly to find the distance between any two position vectors that are entered by the user.
It was tedious to have to assign the two vectors each time before using the above script file. One can combine the assignment of input values with the actual instruction, which invokes the script file by using a function m-file. Not only that, but also one can at the same time assign the answer to an output variable.
To create a new function file, one can open their favorite text editor and type the following commands,
% Calculates the distance between two vectors a and b
% Input: a, b (position vectors)
% Output: dist_ab is the distance between a and b
function dist_ab = distfn(a , b)
d= b – a;
dd = d*d’;
dist_ab = sqrt(dd);
Save these contents in a file named distfn.m and we should now be able to run,
>> dist_ab=distfn([1 2 3], [ 5 5 3])
>> a=[1 2 3];
>> b=[5 5 3];
>> dist_ab=distfn(a , b);
To save a certain part of the work in the MATLAB session, one can type,
>> diary work1
>> diary off
All the work between the diary commands will be saved into a file called work1.
Homework: Create a function file to deduce the maximum length of the side of a triangle ABC whose position vectors are given by a, b, c.
One of the most useful commands in MATLAB is the help command. For e.g., you can type,
>> help sin
>> help sqrt
and so on. Also note that,
>> help distfn
would return the comments that were entered at the beginning of the program written in the session.
To define a matrix you start with its name. Square brackets are used to begin and end each matrix. You can separate elements with a space or a comma, and end each row with a semi-colon like this:
>> A = [1, 2, -6; 7, 5, 2; -2, 1, 0]
>> A = [1 2 -6; 7 5 2; -2 1 0]
In either case you have defined the same 3 by 3 matrix named A and you can use it at any time in a calculation or to define another matrix by using its name (A).
>> B = [2 -4 7 ]
B is a 1 by 3 row matrix
>> C = [2; -4; 7; ]
C is a 3 by 1 column matrix
>>D = [5, 8,-2; 3,-4, 5]
D is a 2 by 3 matrix
You can edit individual elements of a matrix as follows:
>> A(1,1) = -5 changes the element in row1 column1 of matrix A to -5
>> D(2,3) = 0 changes the element in row2 column3 of matrix D to 0
To perform operations on matrices you use the symbols ( +, -, * ) from the number keypad or above the numbers across the top of the keyboard.
>> A + A adds the matrix A to itself.
>> B * C multiplies B and C
>> C*B – A A is subtracted from the product of C and B
The symbol ^ (above the number 6) is used to raise a matrix to an exponent as follows:
>> A^3 cubes the matrix A (you might also use A*A*A for the same calculation)
>> C*D an error message is displayed Matlab will give an error message when the
calculation cannot be done because of a dimension mismatch.
To solve the system of equations for (x, y, z) using Gaussian Elimination:
a x + b y + c z = u
e x + f y + g z = v
p x + q y + r z = w
we perform the following steps in matlab.
>> A = [a b c; e f g; p q r];
>> b = [u; v; w];
>> M = [A b];
>> R = rref(M);
>> X = R(4, 1:3);
More helpful MATLAB commands:
quit or exit either of these closes the program and ends your matlab session.
save filename this command will save all variables (and ONLY the variables – NOT the whole session) that you have defined in the current session. This is helpful when you enter large matrices that you want to work with at a later date.
load filename this command loads the variables that you saved in a previous session.
lpr this is the command used to print your diary file. EXIT THE MATLAB PROGRAM.
At the osf1 prompt, type: lpr -Pst220 filename (note: st220 is the printer in ST I room 220. At other locations you will use another printer name after the –P )
who displays variables you have defined in your current session
why matlab answers the question.(again and again)
clear clears all variables from your current session. Only use this command if you want to lose everything.
% this is used for comments. Matlab ignores any line that begins with %
Matlab has many built in matrix functions and operators. I have listed some here that you may find useful:
>> size(A) gives the dimension of the matrix A
>> inv(A) calculates the inverse of the matrix A , if it exists.
>> det(A) calculates the determinant of the matrix A
>> rref(A) calculates the row reduced echelon form of the matrix A
>> A‘ forms the transpose of the matrix A.
>> eye (2,2) this is the 2 by 2 identity
>> zeros (3,3) builds the zero matrix of any dimension
>> ones (3,2) fills a matrix of any size with ones.
>> rats(A) displays elements of the matrix A as fractions
>> format long displays all numbers with 15 digits instead of the usual 4 digits
Some useful built-in functions:
Elementary trigonometric functions and their inverses
sin, cos, tan, sec, csc, cot, asin, acos, atan, asec, acsc, acot
Elementary hyperbolic functions and their inverses
sinh, cosh, tanh, sech, csch, coth, asinh, acosh, atanh, asech, acsch, acoth
Basic logarithmic and exponentiation functions
log, log2, log10, exp, sqrt, pow
Basic Statistical functions
max, mean, min, median, std, var, sum
Basic complex number functions
imag, real, i, j, abs, angle, cart2pol
Basic data analysis functions
fft, ifft, interpn, spline, diff, del2, gradient
Basic logical functions
and, or, xor, not, any, all, isempty, is*
Basic polynomial operations
poly, roots, residue, polyfit, polyval,conv
Function functions that allows users to manipulate mathematical expressions
feval, fminbnd, fzero, quad, ode23, ode45, vectorize, inline, fplot, explot
Basic matrix functions
zeros, ones, det, trace, norm, eig
Try the following:
Suppose we wish to plot the graph y=x2 in the interval [-1, 1], then just type,
>> x = -1:0.1:1
Note that the axes are automatically chosen to suit the range of variables used. One can add more features to the plot using the following commands:
>> title(‘Graph of y=x^2’)
Suppose now we want to plot the graphs y1=x2 and y2=2x on the same figure, we need,
>> hold on
Note that the hold on command tells MATLAB to retain the most recent graph so that a new graph can be plotted. Note that axes are adjusted and the second curve is plotted with a red circle. More options on the choice for the color and symbol can be found by typing,
>> help plot
Suppose we want to plot the graphs y1=x2 and y2=2x on the same figure but partitioned into two subplots then we say,
One must now be able to employ the various plotting commands in various combinations to get the desired figure.
This allows a group of commands to be repeated a fixed, predetermined number of times. The general form of a for loop is:
for x = array
>> for n=1:10
yields the vector x given by,
Columns 1 through 7
۰٫۳۰۹۰ ۰٫۵۸۷۸ ۰٫۸۰۹۰ ۰٫۹۵۱۱ ۱٫۰۰۰۰ ۰٫۹۵۱۱ ۰٫۸۰۹۰
Columns 8 through 10
۰٫۵۸۷۸ ۰٫۳۰۹۰ ۰٫۰۰۰۰
Let us now use the for loop to generate the first 15 Fibonacci numbers 1,1,2,3,5,8,…
>> f=[1 1];
>> for k=1:15
f(k+2) = f(k+1) + f(k);
This evaluates a group of commands an infinite number of times unlike the for loop that evaluates a group of commands a fixed number of times. The general form for while loop is
For example to generate all the Fibonacci numbers less than 1000, we can do the following:
>> f=[1 1];
>> while f(k) < 1000
f(k+1) = f(k+1) + f(k);
k = k +1;
There are times when a sequence of commands must be conditionally evaluated based on a relational test. This is done by the if-else-end construct whose general form is,
For example if we want to give 20% discount for larger purchases of oranges, we say,
>> oranges=10; % number of oranges
>> cost = oranges*25 % Cost of oranges
>> if oranges > 5
cost = (1-20/100)*cost;
If there are more conditions to be evaluated then one uses the more general if-else-end construct given by,
Commands evaluated if True
Commands evaluated if False
This is used when sequences of commands must be conditionally evaluated based on repeated use of an equality test with one common argument. In general the form is,
Let us now consider the problem of converting entry in given units to centimeters.
% This program converts a given measument into the equivalent in cms
% It illustrates the use of SWITCH-CASE control flow
switch units % convert A to cms
y = A*2.54;
y = A*2.54*12;
y = A*100;
y = A;
disp([‘Unknown units: ‘ units])
y = nan; %% stands for not a number
In MATLAB, these are arrays of ASCII values that are displayed as their character string representation. For example:
>> t = ‘Hello’
A character string is simply text surrounded by single quotes. Each character in a string is one element in the array. To see the underlying ASCII representation of a character string, you can type,
۱۰۴ ۱۰۱ ۱۰۸ ۱۰۸ ۱۱۱
The function char provides the reverse transformation:
Since strings are numerical arrays with special attributes, they can be manipulated just like vectors or matrices. For example,
One can also concatenate strings directly. For instance,
>> u=’My name is ’;
>> v=’Mr. MATLAB’;
>> w=[u v]
My name is Mr. MATLAB
The function disp allows you to display a string without printing its variable name. For example:
My name is Mr. MATLAB
In many situations, it is desirable to embed a numerical result within a string. The following string conversion performs this task.
>> radius=10; volume=(4/3)*pi*radius^3;
>> t=[‘A sphere of radius ‘ num2str(radius) ‘ has volume… of ‘ num2str(volume) ’.’];
It may sometimes be required to find a certain part of a longer string. For example,
>>a=’Texas Tech University’;
>>findstr(a,’ ‘) %% Finds spaces
- ۶ ۱۱
>>findstr(a,’Tech’) %% Finds the string Tech
>>findstr(a,’Te’) %% Finds the string starting with Te
>>findstr(a,’tech’) %% This command is case-sensitive
If it is desired to replace all the case on Tech to TECH then one can do this by using,
Texas TECH University
These include the operators < <= > >= == ~=
These operators can be used to compare two arrays of the same size, or to compare an array to a scalar. For example:
>> A=1:5, B=5-A
۱ ۲ ۳ ۴ ۵
۴ ۳ ۲ ۱ ۰
۰ ۰ ۰ ۱ ۱
finds elements of A that are greater than 3. Zeros appear in the result where this condition is not satisfied and ones appear where it is.
>> for n=2:6
The three main logical operators are: AND, OR, NOT which are represented by the symbols &, |, ~ respectively in MATLAB. Often one can combine these operators with relational expressions. For example:
>> g=(A>2) & (A<5)
۰ ۰ ۱ ۱ ۰
returns ones where A is greater than 2 AND less than 5.
>> for n=2:6
if (rem(n,2)~=0) & (rem(n,3)~=0)
Finally, the above capabilities make it easy to generate arrays representing discontinuous functions, which are very useful in understanding signals etc. The basic idea is to multiply those values in an array that you wish to keep with ones, and multiply all other values with zeros. For example,
>> x = -2:0.1:2; % Creates Data
>> y = ones(size(x));
>> y = (x>-1)&(x<1);
This should plot a function which resembles part of a square wave that is discontinuous at x=-1 and x=1.