MATLAB: Introduction and Programming
Pralay Mitra, Ph.D.
Associate Professor
Department of Computer Science and Engineering
Indian Institute of Technology Kharagpur
Content
History
Introduction
Environment and Workspace
Variables
Operator Precedence
Commands
Mathematical Functions
Basic Plots
Matrix
Matrix Operations
Array Operations
Linear Equations
Programming in MATLAB
History
MATLAB: MATrix LABoratory
Developed primarily by Cleve Moler in the 1970's
Derived from FORTRAN subroutines LINPACK and EISPACK, linear and eigenvalue
systems.
Developed primarily as an interactive system to access LINPACK and EISPACK.
Gained its popularity through word of mouth, because it was not o±cially distributed.
Rewritten in C in the 1980's with more functionality, which include plotting routines.
The MathWorks Inc. was created (1984) to market and continue development of
MATLAB.
Introduction
MATLAB: MATrix LABoratory
Integrate computation (technical), visualization, and programming environment
Programming environment provides sophisticated data structures, debugging tools, and
supports object-oriented programming.
Provides opportunity for tool box: in-built and programmer specific
Strengths
Weakness
Introduction
Starting MATLAB
Double click on the MATLAB icon
It will open and following elements will appear
The Command Window
The Command History
The Workspace
The Current Directory
The Help Browser
The Start button
Environment and
Workspace
Getting Started
>> 4*x
Use as a calculator ans =
>> 1+2*3 28.0000
ans = Closing MATLAB (File -> Exit)
7 >> quit
>> x = 1+2*3
x=
7
Variables
Variable = value or expression
>> x= 5;
>> x = x+10
x=
15
>> 5x
??? 5x
|
Error : Unexpected MATLAB expression
To correct hit the up-key and edit
Operator Precedence
Parentheses (starting from inner most)
Exponentials (associativity left to right)
Multiplications and Divisions (associativity left to right)
Additions and Subtractions (associativity left to right)
Try:
>> 1/(2+3^2)+4/5*6/7
>> 1/2+3^2+4/5*6/7
>>format short Commands
>>x=123.1234
Short is default
>>format long
>>x=1.231233333333333e+002
>> clear
>> who size, space allocation, and class of the variables
>> diary <filename>
>> x=3.14; y = x*2^2, z = 4*x*2 What will be the output?
>> help <command_name>
>> lookfor <function_name>
>> theta = linspace(0,2*pi,101)
Mathematical Function
Basic Plots
>>x=[1 2 3 4 5 6 7 8 9];
>>y=[9 8 7 6 5 4 3 2 1];
>>plot(x,y)
>> clear;
>>x = 0:pi/100:2*pi
>>y=sin(x);
>>plot(x,y)
>>xlabel(‘x=0:2\pi’)
>>ylabel(‘Sine of x’
>>title<‘Plot of the Sine function’)
Basic Plots
Colon Operator
>> A(2,:)
Matrix ans =
456
>>row=[1 2 3 4 5 6 7] >>A=[1 2 3; 4 5 6; 7 8 9] >> A(:,2:3)
row = A= ans =
1234567 123 23
>>col=[1;2;3;4;5;6;7] 456 56
col = 789 8 10
1 >> size(A)
2 ans = >>A(1:end)
3 3 3 ans =
4 >> [m,n]=size(A) ???
5 >>A(2,1)
6 A= >> A(:,2)=[]
7 4 ans =
>>col=row’ >>A(3,3)=10 13
A = ??? 46
7 10
Creating sum-matrix The submatrix comprising the
intersection of rows p to q and columns r
to s is denoted by A(p:q,r:s).
A colon (:) as the row or column specifier
>>A=[1 2 3; 4 5 6; 7 8 9] covers all entries in that row or column;
>> B = A([2 3],[1 2]) thus
?? A(:,j) is the jth column of A, while
>> C = A([2 1 3],:)
A(i,:) is the ith row, and
??
A(end,:) picks out the last row of A.
>> A(:)
??
>> A(2:3,2:3)
??
>> A(end:-1:1,end)
??
Matrix continued
>> B = [A 10*A; -A [1 0 0; 0 1 0; 0 0 1]]
B=
1 2 3 10 20 30
4 5 6 40 50 60
7 8 9 70 80 90
-1 -2 -3 1 0 0
-4 -5 -6 0 1 0
-7 -8 -9 0 0 1
>>help elmat
>>doc elmat
Matrix Operations
A+B or B+A is valid if A and B are of the same size
A*B is valid if A's number of column equals B's number of rows
A^2 is valid if A is square and equals A*A
a*A or A*a multiplies each element of A by a
Array Operations
>> C = A.*B #Element-by-element multiplication
>> C = A./B #Element-by-element division
>> C = A.^B #Element-by-element exponentiation
>> C = A+B #Element-by-element addition
>> C = A-B #Element-by-element subtraction
Linear Equations
>> A = [1 2 3; 4 5 6; 7 8 0];
>> b = [1; 1; 1];
>> x = inv(A)*b #Inverse of a matrix
x=
-1.0000
1.0000
-0.0000
>> det(A) #Determinant
ans =
27
>> x = A\b #Solving linear equations using Gaussian elimination
x=
-1.0000
1.0000
-0.0000
Programming in MATLAB
Introduction
M-file Scripts
M-file functions
Input to a script file
Output commands
Saving Output to a file
Programming in Matlab (M-File Script)
1. Create a file with a list of Your first MATLAB program
>> edit first.m
commands
Add following statement in the file and save it.
2. Save the file (save it with .m A = [1 2 3; 3 3 4; 2 3 3];
extension), b = [1; 1; 2];
x = A\b
3. Run the file. Execute
>> first
x=
-0.5000
1.5000
-0.5000
Next if I type
>>who
Programming in MATLAB (M-File function)
%{
Comments
%}
# Define the function name, and the number and order of input and output arguments
function f = factorial(n)
# A one line summary description of the program, displayed when you request Help
% FACTORIAL(N) returns the factorial of N.
# A more detailed description of the program
% Compute a factorial value.
# Program code that performs the actual computations
f = prod(1:n);
>> f = factorial(5)
f=
120
Programming in MATLAB
Scripts Functions
- Do not accept input arguments - Can accept input arguments and
or return output arguments. return output arguments.
- Store variables in a workspace - Store variables in a workspace
that is shared with other scripts internal to the function.
- Are useful for automating a - Are useful for extending the
series of commands MATLAB language for your
application
I/O arguments
function A=Myfunction(B) #One input argument and one output argument
function area=TrapArea(a,b,h) #Three inputs and one output
function [h,d]=motion(v,angle) #Two inputs and two outputs
Input to a M-file script
1. The variable is defined in the script file.
2. The variable is defined in the command prompt.
3. The variable is entered when the script is executed.
Output command
disp
fprintf
Control Flow (if-else)
discr = b*b - 4*a*c; discr = b*b - 4*a*c;
if discr < 0 if discr < 0
disp('Warning: discriminant is negative'); disp('Warning: discriminant is negative');
end elseif discr == 0
disp('Discriminant is zero')
discr = b*b - 4*a*c; else
disp('Roots are real')
if discr < 0 end
disp('Warning: discriminant is negative');
else
disp('Roots are real, but may be repeated')
end
Control Flow (for and while)
for ii=1:5
x=ii*ii
end
n = 5; A = eye(n);
for j=2:n
for i=1:j-1
A(i,j)=i/j;
A(j,i)=i/j;
end
end
x=1
while x <= 10
x = 3*x
end
Saving output to a file
1. Open a file using fopen
2. Write the output using fprintf
3. Close the file using fclose % write some variable length strings to a file
op = fopen('weekdays.txt','wt');
fprintf(op,'Sunday\nMonday\nTuesday\nWednesday\n');
fprintf(op,'Thursday\nFriday\nSaturday\n');
fclose(op);
Arithmetic operators and special characters
Array operators
Relational and logical operators
Managing Workspace and file commands
Predefined variables and math constants
Elementary matrices and arrays
Arrays and Matrices – Basic Information
Arrays and Matrices – Operations and
Manipulations
Arrays and Matrices: matrix analysis and linear
equations
Programming in Matlab
Read a set of N linear equations For an input value, generate Sine and Cosine
with M unknowns (where N>M). function from 0 to twice PI and plot it with an
Solve it by MATLAB equal interval of 30 degree.
Thank you