Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Introduction To MATLAB

Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

INTRODUCTION TO COMPUTER

PROGRAMING USING MATLAB


WHAT IS MATLAB?
 Matlab is basically a high level language

 It was originally designed for solving linear algebra type problems using
matrices
 It’s name is derived from
MATrix LABoratory
 It has many specialized toolboxes and built-in programs for making things
easier for us
MATLAB MAIN SCREEN
 Command Window: is
where you'll type commands
and give MATLAB its input
and view its output
Current
 Current Directory : Editor
Directory Command
shows folders and m-files History

 Workspace: shows current


working variables and other Command
Workspace
objects. Double click on a Window

variable to see it in the Array


MATLAB MAIN SCREEN

 Command History:
shows past commands
 Editor : is a text Current
Editor
Directory Command
editor where you can History
load, edit and save
Matlab programs. Command
Workspace
Window
VARIABLE
 Variable names are case sensitive
 Variable names can contain up to 63 characters (as of MATLAB R2021a). One can use
namelengthmax command to verify it.
 Variable names must start with a letter followed by letters, digits, and underscores.
 MATLAB variables are defined by assignment.
 All variables are created as matrices with “some” type (unless specified)
 Example
x=1; b=false; c=‘Hello World!’
SPECIAL VARIABLES
ans Default variable name for results
pi Value of π
eps Smallest incremental number
inf Infinity
NaN Not a number e.g. 0/0
i,j imaginary unit i, i.e. square root of -1
realmin The smallest usable positive real number
realmax The largest usable positive real number
ARITHMETIC OPERATIONS

 addition + a + b
 subtraction – a - b
 division / a/b = b\a
 multiplication * a*b
 power ^ a^b
 Assignment = a = b (assign b to a)
LOGICAL OPERATORS

 MATLAB supports five logical operators.

~ element wise/scalar logical NOT


& element wise logical AND
| element wise logical OR
&& logical (short-circuit) AND
|| logical (short-circuit) AND
RELATIONAL OPERATORS
 MATLAB supports six relational operators.

Less Than <


Less Than or Equal <=
Greater Than >
Greater Than or Equal >=
Equal To ==
Not Equal To ~=
OTHER SYMBOLS

... continue statement on next line


, separate statements and data
% start comment which ends at end of line
; suppresses display of value (when placed at end of a statement)
: specify range
SOME USEFUL COMMANDS
 who List known variables
 whos List known variables plus their size
 clear Clear variables from workspace
 clc Clear the command window
 close all Close all figures
MATLAB & MATRICES

 MATLAB treats all variables as matrices.

 Vectors are special forms of matrices and contain only one row OR one column.

 Scalars are matrices with only one row AND one column
ARRAYS AND MATRICES

 v = [-2 3 0 4.5 -1.5]; % length 5 row vector.


 v = v’; % transposes v.
 v(1); % first element of v.
 v(2:4); % entries 2-4 of v.
 v([3,5]); % returns entries 3 & 5.
 v=[4:-1:2]; % same as v=[4 3 2];
 a=1:3; b=2:3; c=[a b];  c = [1 2 3 2 3];
ARRAYS AND MATRICES (2)

 x = linspace(-pi,pi,10); % creates 10 linearly-spaced elements from –pi


to pi.
 A = [1 2 3; 4 5 6]; % creates 2x3 matrix
 A(1,2) % the element in row 1, column 2.
 A(:,2) % the second column.
 A(2,:) % the second row.
ARRAYS AND MATRICES (3)
 A+B, % matrix addition
 A-B,% matrix subtraction
 2*A, %scalar multiplication
 A*B %matrix multiplication
 A.*B % element-by-element mult.
 A’ % transpose of
 det(A) % determinant of A
CREATING SPECIAL MATRICES

 eye(n) % identity matrix of size n.


 zeros(m,n) % m-by-n zero matrix.
 ones(m,n) % m*n matrix with all ones.
MORE MATRIX/VECTOR OPERATIONS

 length(v)% determine length of vector.


 size(A) % determine size of matrix.
 rank(A) % determine rank of matrix.
FOR LOOPS
 x = 0;
for i=1:2:5 % start at 1, increment by 2
x = x+i; % end with 5.
end

This computes x = 0+1+3+5=9.

Can be nested
WHILE LOOPS
 x=7;
while (x >= 0)
x = x-2;
end

This computes x = -1.

 Repeats loop until logical condition returns FALSE.


 Can be nested.
IF STATEMENTS

if (x == 3)
disp('The value of x is 3.');
elseif (x == 5)
disp('The value of x is 5.');
else
disp('The value of x is not 3 or 5.');
end
SWITCH STATEMENT
switch face
case {1}
disp('Rolled a 1');
case {2}
disp('Rolled a 2');
otherwise
disp('Rolled a number >= 3');
end
BREAK STATEMENTS

 break – terminates execution of for and while loops. For nested loops,
it exits the innermost loop only.
GRAPHICS

 x = linspace(-1,1,10);
 y = sin(x);
 plot(x,y); % plots y vs. x.
 title('Plot of y versus x')
 xlabel('Values of x')
 ylabel('Values of y')
 grid
 hold on; % put several plots in the same figure window.
 figure; % open new figure window.
GRAPHICS (2)

plot(x,y,’k-’); % plots a black line of y vs. x.


Colors Line Types
Blue b Solid –
Green g Dotted :
Red r Dashdot -.
Cyan c Dashed –
Magenta m
Yellow y
Black k
creates axes in the position specified by p

GRAPHICS (3)

 subplot(m,n,p)
divides the figure into an mxn
grid and creates axes in the
position specified by p.
EXAMPLES OF MATLAB PLOTS
SCRIPTS AND FUNCTIONS

 Two kinds of M-files:

Scripts, which do not accept input arguments or return output


arguments. They operate on data in the workspace.

Functions, which can accept input arguments and return output


arguments. Internal variables are local to the function.
M-FILE FUNCTIONS

function [area,circum] = circle(r)


% [area, circum] = circle(r) returns the
% area and circumference of a circle
% with radius r.
area = pi*r^2;
circum = 2*pi*r;
end

• Save function in circle.m.


M-FILE SCRIPTS

r = 7;
[area,circum] = circle(r);
% call our circle function.
disp(['The area of a circle having radius ' ...
, num2str(r), ' is ', num2str(area)]);

• Save the file as myscript.m.


STRUCTURE OF A
Keyword: function
FUNCTION M-FILE
Function Name (same as file name .m)
Output Argument(s) Input Argument(s)

function y = ave(x)

% For vectors, ave(x) returns the average.


Online Help % For matrices, ave(x) is a row vector
% containing the average value of each column.

[m,n] = size(x);
if m == 1
MATLAB
m = n;
Code
end
y = sum(x)/m;
end

»output_value = ave (input_value) Command Line Syntax


MATHEMATICAL FUNCTIONS

 sqrt
 log
 cos/acos/sin/asin etc
 exp - exponential
 abs
 sign
 norm
 sum
 prod - product
LOGICAL FUNCTIONS

 xor (a, b) exclusive or


 any(x) returns 1 if any element of x is nonzero
 all(x) returns 1 if all elements of x are nonzero
 isnan(x) returns 1 at each NaN in x
 isinf(x) returns 1 at each infinity in x
 finite(x) returns 1 at each finite value in x
 find(x) find indices and values of non zero elements
INTERACTIVE EXAMPLE (1)

Write a Matlab program to compute the following sum


∑1/i2, for i=1, 2, …, 10
two different ways:
1. 1/1+1/4+…+1/100
2. 1/100+1/81+…+1/1.
SOLUTION
% Forward summation
forwardsum = 0;
for i=1:10
forwardsum = forwardsum+1/(i^2);
end
% Backward summation
backwardsum = 0;
for i=10:-1:1
backwardsum = backwardsum+1/(i^2);
end
MATLAB HELP

 For help, command description :

 help command_name

 helpwin command_name

 doc command_name

 lookfor keyword (search unknown command)

You might also like