Documente Academic
Documente Profesional
Documente Cultură
LESSON OUTCOMES
At the end of this topic, the students will be able: To create a simple program using scripts and function file (M-files). To solve the problems through M-files.
Outline
1.0 Scripts and Functions (M-files)
1.1 M-files
1.1.1 Basic Parts of M-file 1.1.2 Creating a Simple M-File 1.1.3 Solving problem through M-File
1.1 M-files
The MATLAB software provides a full programming language that enables you to write a series of MATLAB statements into a file and then execute them with a single command.
You write your program in an ordinary text file, giving the file a name of filename.m The term you use for filename becomes the new command that MATLAB associates with the program.
The file extension of .m makes this a MATLAB M-file. M-files can be scripts that simply execute a series of MATLAB statements, or they can be functions that also accept input arguments and produce output.
Description Defines the function name, and the number and order of input and output arguments
H1 line
A one line summary description of the program, displayed when you request help on an entire directory, or when you use lookfor
A more detailed description of the program, displayed together with the H1 line when you request help on a specific function Program code that performs the actual computations and assigns values to any output arguments Text in the body of the program that explains the internal workings of the program
Help text
Comments
2. Call the M-file from the command line, or from within an another M-file
c = 8.2109
* it is best to use the same name for function and filename to avoid confusion.
Example 1
Solve the mathematical model of the parachutist problem.
Example 2
Solve the mathematical model of the parachutist problem by using script file.
Solution
In editor file:
g= 9.81; m = 68.1; tf = 2; cd = 12.5; v= g*m/cd*(1-exp(-cd/m*tf))
Run the program through command windor by typing the name of the M-file
>>xxxx
v = 16.4050
Example 3
Solve the mathematical model of the parachutist problem by using function file.
Solution
function velocity = freefall (m,cd,tf) % freefall (m,cd,tf) compute the freefall velocity % input: % m = mass (kg) % cd = drag coefficient (kg/m) % t = time (s) % output: % velocity = downward velocity (m/s) % g = acceleration of gravity g = 9.81; velocity = g*m/cd*(1-exp(-cd/m*tf)); end Save the M-file as stated in the 1st line freefall.m Return to command window and type the saved M-file >> freefall(68.1,12.5,2) ans = .
* You can introduce different argument values