Scripts and Function Files: Introduction To Computer For Engineers
Scripts and Function Files: Introduction To Computer For Engineers
%d integer
%f float
%c character
%s string
%5d a field width of 5 for printing an integer
%10s a field width of 10 for printing a string
%6.2f a field width of 6 with 2 decimal places.
%.3f 3 decimal places.
A MATLAB function file (called an M-file) is a
text (plain ASCII) file that contains a MATLAB
function and, optionally, comments.
The file is saved with the function name and the
usual MATLAB script file extension, ".m".
function [ r , g ] = swap ( c , d )
% The function swap receives two values, swaps them,
r=d;
g=c;
end
function [A, C] = circle(r)
A = pi*r.^2;
C = 2*pi*r;
The function is called as follows, if r 4.
>>[A, C] = circle(4)
A=
50.2655
C=
25.1327
Why write “functions” instead of “scripts”?
• Modular Programming
Break complicated tasks up into pieces(functions).
• Functions can “call” other functions.
This means you don’t have to re-write the code for the function
again and again.
• Variables in Functions are “local”.
All variables in the function are “ local ” by default. That means that if
you have a variable in your workspace with the same name as the
variable in a function, then assigning a value to the variable in the
function has no affect on the variable in the workspace. That is,
a function cannot accidentally change (destroy) the data in your
workspace.
What is a computer program?
Programming –
2. Problem Analysis
• User to input a temperature in Fahrenheit
• Output to the user temperature in Celsius
Click “File” and then “Save As” to name the file “F_to_C.m”.
5. Test and Debug the Code
If the program works correctly then it has no “bugs” so
bring the Matlab editor back up and close out the Matlab
program. Does the program work with only scalar input
or does it work with vector values? (see next slide)
6. Run Code
Since two points determine a linear function we know the
function F_to_C works correctly.
Example
1. Problem Definition
Write a function that computes the time for a falling object to hit the ground.
2. Problem Analysis
Use the fact that
height_t = height_0 + velocity_0* time + 1/2 * g * time* time,
where height_t is the height of the object at any given time (in seconds),
g is the acceleration due to gravity, -9.8 m/s 2. velocity_0 is the velocity at
time = 0.
Therefore to compute the time to impact, set height_t = 0 and solve for time. This equation (after
doing some algebra)can be written as:
This is a quadratic formula in terms of the variable time. This can be solved to give: