Sie sind auf Seite 1von 21

UNIVERSITY OF MARYLAND EASTERN SHORE DEPARTMENT OF MATH AND COMPUTER SCIENCE DR.

AARON RABABAAH TUTORIAL ON MATLAB BASICS FALL 2011 1) MatLab: Matrix Laboratory interpreted vs. compiled

2) Interface Windows

command shell

workspace & current directory

command history

diary fname, diary off

3) Calculator

Arithmetic & logical operations: ^, rem, mod, factorial, gcd, lcm

UNIVERSITY OF MARYLAND EASTERN SHORE DEPARTMENT OF MATH AND COMPUTER SCIENCE DR. AARON RABABAAH TUTORIAL ON MATLAB BASICS FALL 2011 Format: long, short, hex, bank (#.##), rat

>> 0.5714

>> format rat

>> ans

>> 4/7

4) Variables, Matrices, Structures and CellArrays

Declaring variables

Expressions

UNIVERSITY OF MARYLAND EASTERN SHORE DEPARTMENT OF MATH AND COMPUTER SCIENCE DR. AARON RABABAAH TUTORIAL ON MATLAB BASICS FALL 2011 ans

clear, clear x, clear all

who & whos

intmax(uint8), 16, 32, 64, intmin( ,

unsigned int

intmax (int8), 16, 32, 64, intmin ( ,

signed int

realmin, realmax

Matrices: m = [;;;], zeros(nr, nc), ones(nr, nc), rand(nr, nc), randn(nr, nc), eye(nr, nc) (identity)

rand(seed, #) rand(seed, 0), rand(seed, 111), etc.

cat(dim, m1,m2,,mn): concatenation. m1=rand(3,3), m2=rand(3,3), m3=rand(3,3) . x = cat(3, m1,m2,m3 ).

UNIVERSITY OF MARYLAND EASTERN SHORE DEPARTMENT OF MATH AND COMPUTER SCIENCE DR. AARON RABABAAH TUTORIAL ON MATLAB BASICS FALL 2011 Vectors: v = [], 0:1:100, use other functions as in matrices above, transpose ()

Indexing: extract an element, extract a row, a column, a sub mat

Using the end operator: x(1:end)

Linearization of matrices: v = m(:)

fliplr(m) flip left-right, flipud(m) flip up down, flipdim(m,dim) flips m in the direction of dim, dim=1,2,3

helpful in signals and images.

Real matrix operations vs. scalar (element-wise) ops. The .

Advanced mat ops: tril, triu(m) (lower/upper triangles),diag(m), trace(m) =(sum of eigen vals), det=determinant, inv=inverse, eig=eigen vals, svd (singular value decomp), poly(m) =characteristic polynomial of det(lmda.I A), roots(poly(m)) = eigen vector. Same as eig(m). row reduced echelon form: rref(m), rrefmovie(m), rank(m) = number of non-zero rows in the RREF form.

UNIVERSITY OF MARYLAND EASTERN SHORE DEPARTMENT OF MATH AND COMPUTER SCIENCE DR. AARON RABABAAH TUTORIAL ON MATLAB BASICS FALL 2011 length, size, numel (for 2D mat = rows*cols), sum, cumsum (cumulative sum, good CDF from hist or PDF), prod (v), min, max, mean, median, range, std, var, find(v<.1), any(v) (Boolean if any elem is true), all(v) (Boolean if all elems are true), sort(v, 'ascend or descend)

Reshape:

>> x = rand(4,3)

>> y = reshape(x, 12 ,1)

>> z = reshape(y, 4, 3)

Cell: x = {}; x{1} = rand(3), x{2} = 'hello', x{3} = 123, x{4} = 99;

Structure: x=0; x.rndM = rand(3), x.str = hello, x.var = 123

save fname.mat (saves all space), save fname x, load fname

Rounding: round, floor, ceil

UNIVERSITY OF MARYLAND EASTERN SHORE DEPARTMENT OF MATH AND COMPUTER SCIENCE DR. AARON RABABAAH TUTORIAL ON MATLAB BASICS FALL 2011

5) Utility Functions

primes(n): finds all primes <= n

isprime(x)

magic(n): returns a magic square of the size n

pi, eps, inf

pause(n_sec)

clock: CLOCK = [year month day hour minute seconds]

d = fix(clock); 2012

25

10

52

40

6) Symbolic Math

UNIVERSITY OF MARYLAND EASTERN SHORE DEPARTMENT OF MATH AND COMPUTER SCIENCE DR. AARON RABABAAH TUTORIAL ON MATLAB BASICS FALL 2011 Declare symbolic vars: syms x y z

Define a sym function: f = 3*x^2 y^3

whos to see the var types

Subs substitutes, (one var at a time): subs(f, x, 3), subs(f, y, 5) or all at once: subs(f, {x,y}, {3,5})

diff(f,x,order): let f = 5*x^3 17*x^2

int(f,x), int(f,x, x0, x1), limits can be inf, inf

limit: let f = x/abs(x), limit(f,x,0, 'right'), limit(f,x,0,left')

for a given function f= (x-1)*(x-2)*(x-3): collect(f), expand(f), horner(f) (poly nested rep), factor(f).

UNIVERSITY OF MARYLAND EASTERN SHORE DEPARTMENT OF MATH AND COMPUTER SCIENCE DR. AARON RABABAAH TUTORIAL ON MATLAB BASICS FALL 2011 polynomial roots(p): p is coeff vector: f = -1+x^2, roots([-1 0 1]), polyval(p,x): p=coefficients of a polynomial,x=aval at wich the ploy need to be evaluated. e.g. 1+5x-3x^2, p=[3 5 1].

Fzero(fun, x0): fun can be anonymous, string expression or mfile, x0 = initial guess:

m-file: x = fzero(@myfun,x0);

anonymous: x = fzero(@(x)sin(x*x),x0);

string exprn: x = fzero(sin(x*x),x0);

7) Signal Generation

t = -10:.01:10;

x = zeros( length(t), 1 ); plot(t, x)

UNIVERSITY OF MARYLAND EASTERN SHORE DEPARTMENT OF MATH AND COMPUTER SCIENCE DR. AARON RABABAAH TUTORIAL ON MATLAB BASICS FALL 2011 x = ones( length(t), 1 ); plot(t, x)

x = rand( length(t), 1 ); plot(t, x)

% uniform

x = randn( length(t), 1 ); plot(t, x)

% gaussian

x = sin(2*pi*.25*t);plot(t,x)

x = cos(2*pi*.25*t);plot(t,x)

x = square(2*pi*.25*t);plot(t,x)

x = sawtooth(2*pi*.5*t);, plot(t,x)

x = sinc(2*pi*.25*t);plot(t,x)

x = gauspuls(.001*t);, plot(t,x)

x = rectpuls(t);, plot(t,x)

UNIVERSITY OF MARYLAND EASTERN SHORE DEPARTMENT OF MATH AND COMPUTER SCIENCE DR. AARON RABABAAH TUTORIAL ON MATLAB BASICS FALL 2011 x = tripuls(t);, plot(t,x)

How about: combination of different signals, adding simulated uniform noise, Gaussian noise

8) Plotting

Basic: plot(x, y, L-C): L=line/marker symbol: ., -, --, +, *, x, etc. C= line color: r=red, g=green, b=blue, etc.

text(fraction_x [0-1], fraction_y[0-1], text);

xlabel(x-axis')

xlabel('y-axis')

grid on

UNIVERSITY OF MARYLAND EASTERN SHORE DEPARTMENT OF MATH AND COMPUTER SCIENCE DR. AARON RABABAAH TUTORIAL ON MATLAB BASICS FALL 2011 title('my plot x vs. y')

legend: x = rand(10,5); p = plot(x);

for i=1:5

lgnd{i} = strcat( function_, num2str(i) );

end

legend(p, lgnd);

Editing the chart properties using the GUI.

ezplot: let f = 5*x^2 - x^3, ezplot(f), ezplot(f, [-10 10])

v0 = rand(100,1); plot(v0); bar(v0), stem(v0), area(v0), hist(v0), scatter([1:1:length(v0)], v0, [1:1:length(v0)]) = (x,y, size, color)

UNIVERSITY OF MARYLAND EASTERN SHORE DEPARTMENT OF MATH AND COMPUTER SCIENCE DR. AARON RABABAAH TUTORIAL ON MATLAB BASICS FALL 2011 area: v1 = rand(100,1); v2 = 2 * rand(100,1);v3 = 3 * rand(100,1); area([v1 v2 v3])

subplot(nr, nc, which): subplot(2,2,1); plot(v0), subplot(2,2,2); bar(v0), subplot(2,2,3), stem(v0), subplot(2,2,4); hist(v0)

bar3(v0)

bar-colormap:

>> x = rand(1,5);

>> h = bar(x);

>> h_child = get(h,'Children');

>> set(h_child,'CData',x);

plot3: t = -10*pi:pi/100:10*pi;x = t.*cos(t);y = t.*sin(t); plot3(x,y,t);

polar: t = 0:.01:2*pi; polar(t,sin(2*t).*cos(2*t),'--r')

UNIVERSITY OF MARYLAND EASTERN SHORE DEPARTMENT OF MATH AND COMPUTER SCIENCE DR. AARON RABABAAH TUTORIAL ON MATLAB BASICS FALL 2011 meshgid: [x y] = meshgrid([0:.1:2], [0:.2:4]), z = cos(x) .* sin(y); surf(x,y,z)

ezmesh: syms f x y; f = sin(x) * cos(y); ezmesh(f)

Anonymous functions: f = @(x) x^3 x^2 + x; fplot, ezplot, feval(f, val)

Inline functions: no need for syms;

f = inline( 'sqrt(x.^2+y.^2)', 'x','y'); f(5,7)

9) Programming M-Files

function [out] = functionName( in ). Filename must = functionName

sub functions

UNIVERSITY OF MARYLAND EASTERN SHORE DEPARTMENT OF MATH AND COMPUTER SCIENCE DR. AARON RABABAAH TUTORIAL ON MATLAB BASICS FALL 2011 global vs. local vars

if cond

instructions;

else

instructions;

end

Logical operators and numeric systems

==, <, >, <=, >=, ~=, & (&&), | (||), ~, or, and, not, xor, bitor, bitand, bitxor,bitshift(A,nBits): +ve n = right shift, -ve n = left., bitcomp (complement), bitset(A, bitpos, binval), bitget(A, bitpos)

Intmax, min, realmax, min

UNIVERSITY OF MARYLAND EASTERN SHORE DEPARTMENT OF MATH AND COMPUTER SCIENCE DR. AARON RABABAAH TUTORIAL ON MATLAB BASICS FALL 2011 dec2bin(int, nbits), bin2dec(binstring), hex2dec(hexstring), dec2hex(int, nhexdig), base2dec(anybasestring, base): base2dec(10212, 3)

switch var of datatype

case val1

instructions;

case val2

instructions;

case valn

instructions;

otherwise

UNIVERSITY OF MARYLAND EASTERN SHORE DEPARTMENT OF MATH AND COMPUTER SCIENCE DR. AARON RABABAAH TUTORIAL ON MATLAB BASICS FALL 2011 instructions;

end

for i=i0:di:i1

instructions;

end

nested for

for i=1:1:n

for j=1:1:m

disp( m(I,j) );

UNIVERSITY OF MARYLAND EASTERN SHORE DEPARTMENT OF MATH AND COMPUTER SCIENCE DR. AARON RABABAAH TUTORIAL ON MATLAB BASICS FALL 2011 end

end

while condition

instructions;

end

input: x = input('enter x val')

display: display(x): displays var name and the var value

disp: disp(x): displays var value only

fprintf('%6d

%6.3f

%16s \n', 10, 57.782, 'hello')

UNIVERSITY OF MARYLAND EASTERN SHORE DEPARTMENT OF MATH AND COMPUTER SCIENCE DR. AARON RABABAAH TUTORIAL ON MATLAB BASICS FALL 2011 6d: 6 = total width of the decimal num, space-padded

6.3f: 6=width of the int part, .3= ndecimal points (precision), space-padded

16s: n chars, width of the string, space-padded

addpath(dir)

10)

CPU Time

function [dt] = test00(n)

tic;

for i=1:n

UNIVERSITY OF MARYLAND EASTERN SHORE DEPARTMENT OF MATH AND COMPUTER SCIENCE DR. AARON RABABAAH TUTORIAL ON MATLAB BASICS FALL 2011 x = i^10;

end

dt = 1000 * toc;

// time in (ms)

11)

Strings:

sprintf, sscanf, strcat, strfind, strjust, strmatch,

strread, strrep, strtrim, strvcat

for i=1:1:3 strtokn(aaron r. rababaa, , i); end

x = 99; y = 11.88; str = ['another way to write to strings' 'x=' num2str(x) '; y=' num2str(y)]

12)

FileIO:

type fname.x: displays file content on command window

dlmread: m = dlmread(fname.txt)

UNIVERSITY OF MARYLAND EASTERN SHORE DEPARTMENT OF MATH AND COMPUTER SCIENCE DR. AARON RABABAAH TUTORIAL ON MATLAB BASICS FALL 2011 dlmwrite: dlmwrite('txt.txt', rand(9), 'delimiter', '\t', 'precision', '%.3f')

xlsread: m = xlsread('c:\matlab\work\myspreadsheet.xls');

m = xlsread('c:\matlab\work\myspreadsheet.xls','sheet2');

m = xlsread('c:\matlab\work\myspreadsheet.xls','sheet2','a2:j5')

m = xlsread('c:\matlab\work\myspreadsheet.xls',2,'a2:j5')

the 4th call is the same as the 3rd only using sheet index (2) instead of the sheets name.

xlswrite: xlswrite('c:\matlab\work\myspreadsheet.xls',sheet2,'a2:c4')

UNIVERSITY OF MARYLAND EASTERN SHORE DEPARTMENT OF MATH AND COMPUTER SCIENCE DR. AARON RABABAAH TUTORIAL ON MATLAB BASICS FALL 2011