0% found this document useful (0 votes)
10 views

ENG-102 2567 Function 2DPlot

Uploaded by

Tranriss
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

ENG-102 2567 Function 2DPlot

Uploaded by

Tranriss
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Week 9.

Function File and 2D Plot


ENG-102 Computer Programming for Engineer
Semester 1/2567

Lecturer : Prawet Ueatrongchit


Email : [email protected]
Phone Number & Line ID : 081-936-9340
Desk : C304
• Function Programming : When a program needs to carry out a big task, the
most sensible thing to do is breaking up the program into small segmentations
• Function (Divide and Conquer Strategy)

• A segmentation of code is called "function" (or module) which make a


program.
✓ Structured programming
✓ Repetitive work in multiple places on program
✓ Reusable piece of code

• Using one script file for one function of MATLAB

2
• Built-in Function

• Function

3
• User-defined Function is MATLAB set of code that is created by user, saved
as function file and can be used like built-in function
• Function
✓ Function file starts with "function" keyword
✓ Output and Input list can be scalar, vector, or matrix
✓ Function name must follow naming rule
✓ Body of function is set of MATLAB command

4
• Example : The function file of circumference. (circumference.m)

• Function
Save function file with
a name of function

>> circumference([2 3 ; 4 5])

ans =

6.2832 9.4248
12.5664 15.7080

>> circumference
Error using circumference (line 4)
Not enough input arguments.

CAUTION: The first word in the function definition line, function, must be typed in lower case
5
• Example : Calculate a height and velocity of dropping object at final time
which is obtained from acceleration, initial velocity and time
• Function
1 2 Gravity g = 9.80665 m/s2
ℎ = 𝑣0 𝑡 + 𝑔𝑡 t = 5 sec
2 h = 122.583125 m
v = 49.03325 m/s
𝑣 = 𝑣0 + 𝑔𝑡 v * 3600s = 176.5197 km/h

function [h,v] = drop(g,v0,t)


% Computes the height (h) traveled
% and the velocity (v) of a dropped
% object, as function of (g),
% the initial velocity (v0),
% and the time (t).
h = v0*t + 0.5*g*t.^2;
v = v0 + g*t;
end
6
• Example : The function file of drop. (drop.m)

• Function function [h,v] = drop(g,v0,t)


% Computes the height (h) traveled
% and the velocity (v) of a dropped
% object, as function of (g),
% the initial velocity (v0),
% and the time (t).
h = v0*t + 0.5*g*t.^2;
v = v0 + g*t;
end

7
• Example : The function file of find det. (find_det.m) : This function find
a determinant of matrix 2x2 or 3x3
• Function
function result = find_det(x)
[r,c] = size(x);
if r==c & r>=2 & r<=3
result = det(x);
else
disp('Invalid Matrix for det')
end
end

8
• Plot function : In MATLAB can use two vectors for create a 2D visualization.
You can be used in various ways as following
• Function
• 2D Plot
% X and Y must be vector with the same length

9
• Simplest Plot :

• Function >> x = 0:pi/10:2*pi; % 1x21 [0 0.3142 0.6283 … 6.2832]


>> y = sin(x); % 1x21 [0 0.3090 0.5878 … -0.0000]
• 2D Plot >> plot(x,y)

>> x = 0:pi/100:2*pi; % 1x201 [0 0.0314 0.0628 … 6.2832]


>> y = sin(x); % 1x201 [0 0.0314 0.0628 … -0.0000]
>> plot(x,y)

10
• Graph decorate (Colour) : You can modify a graph using LineSpec keyword
of Syntax : plot(x,y,LineSpec) for lineColour, LineWidth, Marker,
• Function LineStyle or etc. ( https://ch.mathworks.com/help/matlab/ref/plot.html )
• 2D Plot
LineColour >> x = 0:pi/10:2*pi;
>> y = sin(x);
>> plot(x,y,'r')

11
• Graph decorate (Width or Thick) :

• Function >> x = 0:pi/10:2*pi;


>> y = sin(x);
>> x = 0:pi/10:2*pi;
>> y = sin(x);
• 2D Plot >> plot(x,y,'LineWidth',3) >> plot(x,y,'r','LineWidth',3)

>> plot(x,y,'LineWidth',3,'r')
Error using plot
String argument is an unknown option.
12
• Graph decorate (Marker) :

• Function >> x = 0:pi/10:2*pi;


• 2D Plot >> y = sin(x);
>> plot(x,y,'+')

13
• Graph decorate (Marker) :

• Function >> x = 0:pi/50:2*pi; >> x = 0:pi/20:2*pi;


>> y = sin(x); >> y = sin(x);
• 2D Plot >> plot(x,y,'r+','markersize',10) >> plot(x,y,'g+','LineWidth',3)

14
• Graph decorate (Style) :

• Function >> x = 0:pi/20:2*pi;


>> y = sin(x);
• 2D Plot >> plot(x,y,'--')

>> plot(x,y,'r:','LineWidth',2)

15
• Graph decorate (Multiple Graphs) : If you want 2 graphs in a single window,
you can use hold on keyword
• Function
• 2D Plot >> x = 0:pi/20:2*pi;
>> hold on % on Graph for multiple

>> y = sin(x);
>> plot(x,y)
>> y = cos(x);
>> plot(x,y,'r-.','LineWidth',2)
>> x = 0:2*pi;
>> y = sin(x);
>> plot(x,y,'k*')
>> hold off % off Graph for new

Plot a new graph, previous window will be replaced by a new plot.

16
• Graph decorate (Multiple Graphs) : you can use a single plot command to
plot multiple graphs as well
• Function >> x1 = 0:pi/20:2*pi;
• 2D Plot >> x2 = 0:2*pi;
>> y1 = sin(x1);
>> y2 = cos(x1);
>> y3 = sin(x2);
>> plot(x1,y1,x1,y2,'r-.',x2,y3,'k*')

17
• Graph decorate (Multiple Graphs) : you can’t use LineWidth for each plot

• Function >> plot(x1,y1,x1,y2,'r-.','LineWidth',2,x2,y1,'k*')


• 2D Plot Error using plot
String argument is an unknown option.
>> plot(x1,y1,x1,y2,'r-.',x2,y1,'k*','LineWidth',2)

18
• Graph decorate (Multiple Graphs) : you can use a multiple plot command to
plot multiple graphs on one window by Function : subplot()
• Function
• 2D Plot

19
• Graph decorate (Multiple Graphs) : by subplot() plot() and figure

• Function >>
>>
x1
x2
=
=
0:pi/20:2*pi;
0:2*pi;
• 2D Plot >> y1 = sin(x1);
>> y2 = cos(x1);
>> y3 = sin(x2);

>> figure
>> plot(x1,y1)

>> figure
>> subplot(2,2,1);
>> plot(x1,y1)
>> subplot(2,2,2);
>> plot(x1,y1,x2,y3,'k*');
>> subplot(2,2,3);
>> plot(x1,y1,x1,y2,'r-.');
>> subplot(2,2,4);
>> plot(x1,y1,x1,y2,'r-.',x2,y3,'k*');
20
• Graph decorate (Find Peaks) : you can find point of peak to peak by Function
: findpeaks()
• Function
• 2D Plot

21
• Graph decorate (Find Peaks to Peaks)

• Function clear % Remove items from workspace


• 2D Plot clf % Clear current figure window
clc % Clear Command Window

y = [1 6 3 5 4];

[maxPeak locMax] = findpeaks(y);


[minPeak locMin] = findpeaks(-y);

plot(y)
hold on
plot(locMax,maxPeak,'r*','markersize',20)
plot(locMin,-minPeak,'k*','markersize',20)

22
• Formatting Plots : you can formatted to have a required appearance with
formatting Title, Axis-Labels, Axis-Ranges, Legend, Text-Blocks
• Function and Grid
• 2D Plot
• Formatting
Plots

23
• Formatting Plots (Commands):

• Function title('string') Adds the string as a title at the top of the plot.
• 2D Plot xlabel('string') Adds the string as a label to the x-axes.
• Formatting
ylabel('string') Adds the string as a label to the y-axes.
Plots
axis([xmin,xmax,ymin,ymax]) Sets the minimum and maximum limits of the
x-axes and y-axes.

legend('str1','str2','str3') Creates a legend using the strings to label


various curves (when several curves are in
one plot). The location of the legend is
specified by the mouse.

text(x,y,'string') Places the string (text) on the plot at


coordinate x, y relative to the plot axes.

24
• Example : Plots without format

• Function >> x = 10:0.1:22;


>> y = 95000./x.^2;
• 2D Plot >> xd = 10:2:22;
• Formatting >> yd = [950 640 460 340 250 180 140];
Plots >> hold on
>> plot(x,y,'-','LineWidth',1)
>> plot(xd,yd,'ro--','linewidth',1,'markersize',10)

25
• Example : Formatting Title, Axis-Labels and Text-Blocks
>> title('Light Intensity as a Function of Distance','fontname','Arial','FontSize',14)
• Function >>
>>
xlabel('DISTANCE (cm)')
ylabel('INTENSITY (lux)')
• 2D Plot >> text(14,700,'Comparison between theory and experiment.','EdgeColor','r','LineWidth',2)

• Formatting
Text Alignment
Plots The default alignment is
'HorizontalAlignment','left'

'VerticalAlignment','middle'

26
• Example : Formatting Plots
>> axis([8 24 0 1200]) "0" means showing inside
• Function >> legend('Theory','Experiment',0) the axis in the best position.

• 2D Plot
• Formatting
Plots

27
• Position for Legend

• Function
• 2D Plot
• Formatting
Plots
>> help legend

28

You might also like