Professional Documents
Culture Documents
INTRODUCTION
A function is a code segment which accepts certain inputs. These inputs are
called its arguments. The function written in m-file manipulates the inputs in
the manner in which code is written and provides the required results. Matlab
provides us with the facility that we can also write functions ourselves to
perform specific operation according to our requirement.
We have to make two functions:
(i)
(ii)
PROGRAMMING
plotTriangle Function
Matlab Code:
function plotTriangle(a,b,c)
precision=500;
abx=linspace(a(1),b(1),precision);
aby=linspace(a(2),b(2),precision);
bcx=linspace(b(1),c(1),precision);
bcy=linspace(b(2),c(2),precision);
cax=linspace(c(1),a(1),precision);
cay=linspace(c(2),a(2),precision);
hold on
plot(abx,aby,'-b','linewidth',3)
plot(bcx,bcy,'k-','linewidth',3)
plot(cax,cay,'r-','linewidth',3)
axis([0 10 0 10])
grid on
title('My Triangle')
xlabel('X Values (units)')
ylabel('Y Values (units)')
shiftTriangle Function
Matlab Code:
function [a,b,c]=shiftTriangle(a,b,c,shift)
precision=500;
a=a+shift;
b=b+shift;
c=c+shift;
abx=linspace(a(1),b(1),precision);
aby=linspace(a(2),b(2),precision);
bcx=linspace(b(1),c(1),precision);
bcy=linspace(b(2),c(2),precision);
cax=linspace(c(1),a(1),precision);
cay=linspace(c(2),a(2),precision);
hold on
plot(abx,aby,'-b','linewidth',3)
plot(bcx,bcy,'k-','linewidth',3)
plot(cax,cay,'r-','linewidth',3)
axis([0 10 0 10])
grid on
title('My Triangle')
xlabel('X Values (units)')
ylabel('Y Values (units)')
my_script.m File
Matlab Code:
clc;clear all;close all;
x=[1 2];
y=[1 6];
z=[6 2];
shift=[2 4];
plotTriangle(x,y,z)
[xx,yy,zz]=shiftTriangle(x,y,z,shift);
Results
1-Result of plotTriangle([1 2],[1 6],[6 2])
My Triangle
10
9
8
Y Values (units)
7
6
5
4
3
2
1
0
5
X Values (units)
10
10
9
8
Y Values (units)
7
6
5
4
3
2
1
0
5
X Values (units)
10
My Triangle
10
9
8
Y Values (units)
7
6
5
4
3
2
1
0
5
X Values (units)
10
Conclusion
In this Lab I have learnt the use of Function in programming. Once a
function is programmed, it can be used anywhere in our program. The
greatest advantage of function is that, if a similar task is to be performed
again and again, we don/t have to write the program every time. We can call
the function
Also, it can be observed that function variables are not Global. They just
work within the function and not stored in MATLAB Work Space.
Additionally, I have learnt the use of linspace command of MATLAB. It
converts the points into vectors with desired data points in between. Also the
hold on command is used to draw multiple plots on same figure.