IF statement, Loops and Functions in Matlab  

Posted by shashank in

Switching back and forth from one programming language to the other usually makes me forget the basic commands. Hence the post.

IF statement in Matlab: (Source: http://www.cyclismo.org/tutorial/matlab/if.html)

a = 2;
b = 3;
if (a<b)
j = -1;
end

For Loop in Matlab: (Source: http://www.cyclismo.org/tutorial/matlab/control.html)
>> v = [1:3:10]

v =

1 4 7 10

>> for j=1:4,
v(j) = j;
end
>> v

v =

1 2 3 4

Functions in Matlab: (Source: http://web.cecs.pdx.edu/~gerry/MATLAB/programming/basics.html)

The following 2 functions have to be stored in the files name traparea.m and cart2plr.m respectively. One can include auxiliary functions in the same file but the scope of such functions ends
 function area = traparea(a,b,h)
% traparea(a,b,h) Computes the area of a trapezoid given
% the dimensions a, b and h, where a and b
% are the lengths of the parallel sides and
% h is the distance between these sides

% Compute the area, but suppress printing of the result
area = 0.5*(a+b)*h;

Finally, here is another simple function, cart2plr.m, with two input parameters and two output parameters.

 function [r,theta] = cart2plr(x,y)
% cart2plr Convert Cartesian coordinates to polar coordinates
%
% [r,theta] = cart2plr(x,y) computes r and theta with
%
% r = sqrt(x^2 + y^2);
% theta = atan2(y,x);

r = sqrt(x^2 + y^2);
theta = atan2(y,x);

The following are 2 more examples: (Source: Matlab Help)
Example 1
The existence of a file on disk called stat.m containing
this code defines a new function called stat that calculates
the mean and standard deviation of a vector:

function [mean,stdev] = stat(x)
n = length(x);
mean = sum(x)/n;
stdev = sqrt(sum((x-mean).^2/n));

Example 2
avg is a subfunction within the file stat.m:


function [mean,stdev] = stat(x)
n = length(x);
mean = avg(x,n);
stdev = sqrt(sum((x-avg(x,n)).^2)/n);

function mean = avg(x,n)
mean = sum(x)/n;

This entry was posted on Wednesday, November 4, 2009 at 8:16 PM and is filed under . You can follow any responses to this entry through the comments feed .

0 comments

Post a Comment