Matlab Tutorial
Matlab Tutorial
Matlab Tutorial
Matlab Tutorial
1
2
Overview
Environment
Command Window
Editor Window
Variables
History
5
• Special Vars:
ans, beep, pi, eps, inf, NaN, i, j, nargin, nargout, realmin, realmax,
bitmax, varargin, varargout
• Reserved Words
for end if while function return elseif case otherwise switch
continue else try catch global persistent break
• Operators: + - * / \ ^
• Comments: EDU>> a=b+c; % this is a comment
7
Array Construction
Array Construction Summary Standard arrays
m-files
Functions
Function Syntax
function a = functionName(arg1, arg2, ...)
function [a, b, c] = functionName(arg1, arg2, ...)
Function Documentation
EDU>> open linspace
• Documenting
functions is good EDU>> help linspace
code practice
– Eases maintenence
to you and others function y = linspace(d1, d2, n)!
%LINSPACE Linearly spaced vector.!
• Purpose of the % LINSPACE(X1, X2) generates a row vector of 100 linearly!
function % equally spaced points between X1 and X2.!
%!
• Example of useage % LINSPACE(X1, X2, N) generates N points between X1 and X2.!
• What are the inputs/ % For N < 2, LINSPACE returns X2.!
%!
outputs % Class support for inputs X1,X2:!
• Any issues, % float: double, single!
%!
limitations, suggested % See also LOGSPACE, :.!
improvements.
% Copyright 1984-2004 The MathWorks, Inc. !
• Initial continuous % $Revision: 5.12.4.1 $ $Date: 2004/07/05 17:01:20 $!
comments are
displayed with help if nargin == 2!
n = 100;!
funcName end!
n = double(n);!
y = [d1+(0:n-2)*(d2-d1)/(floor(n)-1) d2];floo!
14
• x=1:0.1:10;
• plot(x)
• plot(x,sin(x))
• General: plot(x,y,’S’)
– S is color, symbol, line style
– Example: plot(x,y,’gx--’);
Multiple Plots
3
16
Subplot
• Subplot allows
multiple plots in a
matrix format
• subplot(nx,ny,pos)
activates an nx by ny
matrix of plots with
plot pos selected
17
Labeling, Formatting
18
Conditionals
• Relational Operators: • Conditionals:
– <, <=, >, >=, ==, ~= if expression if expression if expression
(command) (command) (command)
– (a+b) == (c+d) else elseif expression
end
– B - (A>2) (command) (command)
end else
• Logical Operators: (command)
end
– and: &, or: |, not: ~
– (a>2) & (a<6)
• Switch-Case
switch expression
case test_1
(commands)
case {test_2, test_2}
(commands)
otherwise
(commands)
end
20
Loops
for x = array for i = 1:10
(commands) x(i)=sin(i)
• loops offer explicit control end end
over element assignment and
other operations
for i = 1:10
• Preallocate arrays before for j= 1:3
loops. A(i,j) = i^2 + j^2;
• Loops can be nested end
end
• break statement
• Avoid for loops whenever i = 1:10;
j = 1:3;
there is an equivalent array [ii,jj] = meshgrid(i,j);
approach. A = ii.^2 + jj.^2;
– Vectorized solutions are
often orders of magnitude
faster! tend = 10;
– less typing, easier to read, t = 0;
more intuitive dt = 1.1;
while t < tend
• While loops execute till some (commands)
expression holds t = t + dt;
end
21
β PDF Example
β PDF Example
25
Summary