You are on page 1of 24

MATLAB

Vinod Saini

Outline

Day-3
Debugging
Useful Instructions
try- catch and eval function
Techniques to Improve Performance
3D Plotting
Curve Fitting
Symbolic Toolbox
GUI

Debugging

Set Breakpoints

to pause the execution of a MATLAB file so you can examine the value or variables

Debugging

Clear Breakpoint
Clear Breakpoint in all the files
Step
Step in
Step out
Continue
Exit debug
Working directory

Debugging

Some useful instructions

[M, N] = size(X);

isnan(X)

for matrix X, returns the number of rows and columns in X as separate output variables.
N = size(X, 2) - number of columns
M = size(A,1) number of rows
returns an array that contains 1's where the elements of X are NaN's and 0's where they
are not. For example, isnan([pi NaN Inf -Inf]) is [0 1 0 0].

isinf(X)
clearvars X*

Clear variables which start with X


clearvars X; clear only variable X
clearvars -except X*; clear variables which are not starting with X

Some useful instructions

disp(X)

abs(X)

returns logical 1 (true) if X is an empty array and logical 0 (false) otherwise

ls

Absolute value of X

isempty(X)

Display array or string

lists the contents of the current folder.


ls *.m

pwd

returns the current folder as a character vector to currentFolder.

Some useful instructions

mkdir

rmdir

rmdir(folderName) removes the folder folderName from the current folder if folderName
is empty

cd / cd..
who

mkdir('folderName') creates the folder folderName

who lists in alphabetical order the names of all variables in the currently active
workspace.
who -file filename lists the variable names in the specified MAT-file.

what

what lists the path for the current folder and all the MATLAB relevant files and folders
found in the current folder

Some useful instructions

csvread

M = csvread(filename) reads a comma-separated value (CSV) formatted file into array M.


The file must contain only numeric values.

M = csvread(filename,R1,C1) reads data from the file starting at row offset R1 and column
offset C1.

csvwrite

csvwrite(filename,M) writes matrix M into filename as comma-separated values.

csvwrite(filename,M,row,col) writes matrix M into filename starting at the specified row


and column offset.

xlswrite

xlswrite(filename,A) writes matrix A or cell A to the first worksheet in excel

xlsread

num = xlsread(filename,sheet) reads the specified worksheet.

Plotting Functions

surf /mesh

surf(X,Y,Z) uses Z for the color data and surface height. X and Y are vectors or matrices
defining the x and y components of a surface.
Plot of sinc (z=sin(r)/r )function
[X,Y] = meshgrid(-8:.5:8); % [X,Y] = meshgrid(x,y) returns 2-D grid coordinates based on the
coordinates contained in vectors x and y
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
figure
mesh(Z)
figure
surf(X,Y,Z)

Curve Fitting

Data Types

char

Character array
Str = Hello; Str = [Hello; Everyone;];
k = findstr(str1, str2)

= 'Find the starting indices of the shorter string.';


findstr(s, 'the')
ans = 6 30
strcat(str1,str2) => Concatenate strings horizontally
strvcat(t1, t2, t3, ...) => Concatenate strings vertically
str2double(str)
double2str(x)/ num2str(x)

Data Types

cell

To be used when you want to have different types of data types (char, integer)
Useful when you are writing an excel file
C = cell(dim) => create cell array of dimension dim
A = cell2mat(C) => convert cell to matrix
mat2cell, num2cell

struct

To define a variable having different kind of features


Employee: Vinod, Karthikeyan, Himanshu, Madhu
Employee has Name, salary, joining date, qualification, education

Employee = struct('Name',{'Vinod', 'Karthikeyan', 'Himanshu', 'Madhu'}, 'JoiningDate',


{'12Aug','15Aug','18Aug','1Sep'},'salary',{10,14,10,10},'Education',{'MTech',PhD,'MTec
h',BTech})

Data Type

Employee

Employee(1)

= 1x4 struct array with fields:


Name
JoiningDate
Salary
Education
Name: 'Vinod'
JoiningDate: '12Aug'
salary: 10
Education: 'MTech'

Employee(1).salary

10

try and catch

Execute statements and catch resulting errors

Syntex

Try
Statements
catch exception
Statements
end

try and catch

Divide two arrays of different size

You can't use A./B : works only if A and B are of same length (./ element wise division)

>> edit trycatch.m


clear all; clc;
A = 1:10;
B = 1:9;
for i = 1:length(A)
try
div_AB(i) = A(i)/B(i);
catch
div_AB(i) = A(i)/B(i-1);
end
end

eval function

eval Execute string with MATLAB expression.

Syntex
eval(EXPRESSION)
evaluates the MATLAB code in the string EXPRESSION.

Use

To automate the scripts


Create and define variables on its own

eval function
edit evalexample.m
number_of_variables = 10;
for i = 1:number_of_variables
str = ['X_' num2str(i) '=' num2str(i) ';'];
% str = 'X_1 = 1;'
eval(str)
end

Techniques to Improve Performance

Use functions instead of scripts. Functions are generally faster.


Avoid redundant computation
Avoid global variables
Avoid using "data as code", save them as a mat file and load the mat file
Avoid functions such as eval, evalc, evalin, and feval(fname
Preallocate Instead of continuously resizing arrays, consider
preallocating the maximum amount of space required for an array.

X = zeros(20,1) or X = nan(20,1)

Techniques to Improve Performance

Vectorize Instead of writing loop-based code, consider using MATLAB


matrix and vector operations. Avoid for loops

Symbolic Toolbox

x = sym('x') creates symbolic variable x or syms x.


A = sym('a', n) creates an n-by-n symbolic matrix filled with automatically
generated elements.
A = sym('a', [n1 ... nM]) creates an n1-by-...-by-nM symbolic array filled
with automatically generated elements.
Writing an expression

syms a b c x
f = a*x^2 + b*x + c;

Creating symbolic functions

syms f(x, y) : This syntax creates the symbolic function f and symbolic variables x and y
f(x, y) = x^2 + y^2
f(2,2)

Symbolics Toolbox

Can be defined as matrix

Differentiation

syms x;
f(x) = [x x^2; x^3 x^4];
f(2)
syms x y a b c f
f=a*x^3+b*x+c*y^2
diff_fx = diff(f,x); diff_fy = diff(f,y)
simple(diff_f) => if the differentiation looks complex

Integration

int_f = int(f,x)
int_f = int(f,x,-1,1) (definite integrals )

Symbolics Toolbox

Substitution

clear, clc, syms a c x; g = exp(-a*x)*sin(c*x), int_def_g = int(g,x,-pi,pi)


int_sub=subs(int_def_g,{a,c},{2,4})

Solving Equation

clear, clc, syms x a b c;


eq = 'a*x^2+b*x+c = 0';
[x]=solve(eq,x);
subs(x,{a,b,c},{1,2,1})
Or
syms x a b c;
expn = a*x^2 + b*x + c;
[x]=solve(expn, x)

References

Matlab Image Processing Toolbox:


http://www.cs.otago.ac.nz/cosc451/Resources/matlab_ipt_tutorial.pdf
http://in.mathworks.com/support/learn-with-matlab-tutorials.html
http://www.math.ucsd.edu/~bdriver/21d-s99/matlab-primer.html
http://in.mathworks.com/help/matlab/index.html
http://www.ee.columbia.edu/~marios/matlab/Writing_Fast_MATLAB_Code
.pdf
http://in.mathworks.com/help/matlab/matlab_prog/techniques-for-impro
ving-performance.html
http://www.ee.columbia.edu/~marios/matlab/MatlabStyle1p5.pdf
www.clarkson.edu/~wilcox/ES100/symbtut.doc
List compiled by Prof. Ajit Rajwade

You might also like