User Tools

Site Tools


matlab:matlab_examples

MATLAB m-file Examples

Simple script

the_answer.m
disp('What is the answer to ... everything?')
a = input('> ');
 
disp(['You said ' num2str(a) '.']);
 
if a == 42,
  disp('That is correct.');
else
  disp('That is not correct.');
end;

Function m-file

Ref.1)

traparea.m
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;
end

m-files with "main" function

Ref.2)

compute_trapezoid.m
function main
    area1 = traparea(1,2,3)
    disp(area1)
end
 
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;
end

Ref.3)

quads.m
function main()
    [root1, root2] = quadratic(1, sqrt(2), 1);
    disp(root1);
    disp(root2);
end
 
function [x1, x2] = quadratic(a, b, c)
% [x1, x2] = quadratic(a, b, c)
% Return the roots of a*x^2 + b*x + c.
% Roots may be complex.
 
d = disc(a, b, c);
x1 = (-b + sqrt(d)) / (2*a);
x2 = (-b - sqrt(d)) / (2*a);
end
 
function dis = disc(a,b,c) 
% dis = disc(a,b,c)
% Return the discriminant of a, b, c.
dis = b^2 - 4*a*c;
end

Returning multiple values

Ref.4)

c_to_p.m
function main
  [r, th] = cart2plr(30, 40);
  disp(r);
  disp(th);
end
 
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);
end

Nested loop

nested.m
for i = 1:10
    for j = 1:10
        if j <= i,
            val = 0;
        else
            val = 1;
        end
        my_matrix(i, j) = val;
    end;
end;
 
disp(my_matrix);
1) , 2) , 4)
Recktenwald, Gerald. “MATLAB Functions – Basic Features.” MATLAB Functions – Basic Features. Accessed April 30, 2016. http://web.cecs.pdx.edu/~gerry/MATLAB/programming/basics.html.
3)
Unknown
matlab/matlab_examples.txt · Last modified: 2016/05/04 02:56 by mithat