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

Scripts and Function Files: Introduction To Computer For Engineers

Here is a function that calculates the length L and total fence length given the width W and enclosed area A of a fenced field: function [L, fence_length] = field_fence(W, A) L = sqrt(2*A/W); % Use area formula to solve for length fence_length = 2*L + 2*W; % Total fence length is perimeter end To test it: [L, fence_length] = field_fence(6, 80) L = 10 fence_length = 32

Uploaded by

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

Scripts and Function Files: Introduction To Computer For Engineers

Here is a function that calculates the length L and total fence length given the width W and enclosed area A of a fenced field: function [L, fence_length] = field_fence(W, A) L = sqrt(2*A/W); % Use area formula to solve for length fence_length = 2*L + 2*W; % Total fence length is perimeter end To test it: [L, fence_length] = field_fence(6, 80) L = 10 fence_length = 32

Uploaded by

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

Introduction to Computer for Engineers

Scripts and function files


 A MATLAB script file (Called an M-file) is a text
(plain ASCII) file that contains one or more MATLAB
commands and, optionally, comments.
The file is saved with the extension ".m".
When the filename (without the extension) is issued as
a command in MATLAB, the file is opened, read, and
the commands are executed as if input from the
keyboard.

There is no input or output arguments .


 script.m
 radius = 5;
 area=pi*(radius^2)

 There are two ways to view a script:


◦ type
◦ Editor window

 >> type script


 From Command Window type the name of the file
 >> script

 Or double-click on the file in the list of the current


folder.
 var= input(‘String name’)

 if string or character is desired, ‘s’ can be used


 Use can use quotation marks around the string:
 disp(‘name of a variable’)
 disp(‘text as string’)
 >>disp(‘Hello’)
 >>disp(2^3)
 To display text, the fprintf command has the form
fprintf(‘text as a string’)
 fprintf(‘The value is %d : \n’, 2^3)
 The value is 8.

 %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".

 A MATLAB function may be called from the


command line or from any other M-file.
• When the function is called in MATLAB, the file
is accessed, the function is executed, and control is
returned to the MATLAB workspace.
• Since the function is not part of the MATLAB
workspace, its variables and their values are not
known after control is returned.

• Any values to be returned must be specified in the


function syntax.
 a function accepts input from and returns output to
its caller, whereas scripts do not.
You define MATLAB functions in a file that
begins with a line containing the function key
word.
You cannot define a function within a script file
or at the MATLAB command line.
Example
function [ a , b ] = swap ( a , b )
% The function swap receives two values, swaps them,
temp=a;
a=b;
b=temp;
end

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 –

• A process for obtaining a computer solution to a


problem.

• A computer program is a sequence of


instructions that tell the computer what to do.
Programming Steps
1. Problem Definition
2. Analyze the problems
(i.e. write down the appropriate equations, determine the
user input and user output, ….)
3. Develop Algorithm
(processing steps to solve problem)
4. Write the "Program" (Code)
(instruction sequence to be carried out by the computer)
5. Test and Debug the Code
6. Run Code
Example
1. Problem Definition
Write a function that converts a temperature in Fahrenheit to
Celsius.

2. Problem Analysis
• User to input a temperature in Fahrenheit
• Output to the user temperature in Celsius

Use the fact that celsius = (fahr - 32) * 5/9


3. Develop Algorithm (processing steps to solve
problem)

User inputs a single number


or vector of numbers that
represent temperature in Fahrenheit
Assign those temperatures to the variable
“fahr”

Calculate a new variable called “celsius”


Using the following formula
celsius = (fahr - 32) * 5/9

Output to the user the calculated


temperatures in celsius
4. Write the “Function" (Code)
(instruction sequence to be carried out by the
computer)
Any sequence of Matlab commands can be put in a file.
The file suffix should end with a “.m”. The sequence of commands
will be executed (from the top of the file down, command by
command). Open the Matlab editor and create a new file. Then type
(and save) the following:

function celsius = F_to_C(fahr)


% This function converts Fahrenheit to Celsius.
celsius = (fahr -32)*5/9;

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:

0 = height_0 + velocity_0 * time + 1/2 * g * time * time

This is a quadratic formula in terms of the variable time. This can be solved to give:

 velocity _ 0  velocity _ 0 2  2 * g * height _ 0


time 
g
User inputs: initial height (height_t) and initial velocity (velocity_0)
User outputs: time to hit ground (time)
3. Develop Algorithm (processing steps to solve problem)

User inputs two single number


or vector of numbers that
represent the initial height of the object
(height_0), and initial velocity (velocity_0)

Calculate a new variable called time


Using the following formula
 velocity _ 0  velocity _ 0 2  2 * g * height _ 0
time 
g

Check to see if the values make sense

Output to the user the calculated


Time values
4. Write the “Function" (Code) (instruction sequence to be carried out by
the computer)
Use the Matlab editor to create a file “time_to_impact.m” .
5. Test and Debug the Code
Although the value of the function is assigned to the variable time,
when you execute the function you can assign the value of the
function to any variable.(see next slide)
1. Write a script to calculate the hypotenuse of a square
triangle.

2. Write a function to calculate the hypotenuse of a square


triangle.
 A fence around a field is shaped as shown in Figure
P12. It consists of a rectangle of length L and width
W, and a right triangle that is symmetrical about the
central horizontal axis of the rectangle. Suppose the
width W is known (in meters) and the enclosed area A
is known (in square meters). Write a user-defined
function file with W and A as inputs. The outputs are
the length L required so that the enclosed area is A
and the total length of fence required.
 Test your function for the values W=6m and A=80m2.

You might also like