Matlab_09a
Functions
We are now going to create a few functions.
To make the first example easy I supply the text for you to copy and paste below. Select
File -> New -> M File
to create a blank page and paste in this text:
function cost_to_destination = mypetrolcost(distance_to_destination)
% this is the function equivalent of the
% calculation we explored in matlab_03
%
cost_per_litre = 1.1;
miles_per_litre = 5;
cost_to_destination = distance_to_destination / miles_per_litre * cost_per_litre;
end
Save the file and give it *exactly the same name as the function*! This file must be called mypetrolcost.m or there will be loads of problems later.
Your function can now be executed from the command line like this:
>> mypetrolcost(100)
ans =
22
Notice that by creating and saving a function we have extended the language of Matlab - we have used Matlab to write a new capability for Matlab.
Here is another example we have seen from an earlier exercise.
To make this easy I also supply the text for you to copy and paste below. Select
File -> New -> M File
to create a blank page and paste in this text:
function r = mygraph(x)
y_1 = x.*x; % this gives us x squared
y_2 = x.*x.*x; % this gives us x cubed
plot(x,y_1,'r'); % plot the x squared graph
hold on; % hold the plot for a second line
plot(x,y_2,'g'); % plot x cubed
%
% some extra things added to the graph
xlabel('x values');
ylabel('y values');
title('my first graph')
legend({'x^2' 'x^3'});
grid on;
end
Save the file and give it *exactly the same name as the function*! This file must be called mygraph.m
Your function can now be executed from the command line like this:
>> mygraph(100:1:200)