Você está na página 1de 7

Lab 3 Programming in MATLAB

Script Files
So far, all the commands were executed in the command window. Although every command can
be executed in this manner, using the command window to execute a series of commands-
especially if they are related to each other is not convenient and may be difficult or even
impossible. The problem is that the command window cannot be saved for future purpose for
execution. In addition, command window is not interactive. This means that every time the ENTER
key is pressed only the last command is executed, and everything executed before is unchanged.
If a change or a correction is needed in a command previously executed and the results if this
command are used in commands that follow, all the commands have to be entered and executed
again.
A different way of executing commands, with MATLAB is first to create a file with a list of
commands, save it, and then run a file. While the file runs, the commands it contains are executed
in the order that they are listed. If needed, corrections/changes can be made to the commands in
the file and the file can be saved and run again. Such files are called Script Files.
Example: Develop a script file to compute the velocity of the free-falling bungee jumper for the
case where the initial velocity is zero.

Given: g = 9.81; m = 68.1; t = 12; Cd = 0.25

Solution:
Open the editor with the menu selection: File, New, M-file.
Type in the following statements to compute the velocity of the free-falling bungee jumper at a
specific time
g = 9.81; m = 68.1; t = 12; cd = 0.25;
v = sqrt(g * m / cd) * tanh(sqrt(g * cd / m) * t)

Save the file as scriptdemo.m. Return to the command window and type
>>scriptdemo
The result will be displayed as
v =
50.6175
Thus, the script executes just as if you had typed each of its lines in the command window.
Point to remember about Script Files
1. A script file is a sequence of MATLAB commands, also called a program
2. When a script file runs, MATLAB executes the commands in the order they are written
just as if they were typed in the command window
3. When a script file has a command that generates an output (e.g. assignment of a value to a
variable without a semicolon at the end), the output is displayed in the command window
4. Using a script file is convenient because it can be edited and can be executed many times

Page 1 of 7
5. Script files can be typed and edited in any text editor and then pasted into the MATLAB
editor
6. Script files are also called M-files because the extension .m is used when they are saved.
7. The names of user defined variables, pre-defined variables, MATLAB commands or
functions should not be used to name script files
8. The comments in a script file (which are not to be executed) should begin with % sign.
Write a script file in MATLAB
%Example of a script file
%This program calculates the square root of the numbers 1 through 10
% It displays a vector x with the numbers 1 through 10
% and the vector y with the square root
x = [1:10] %Define a vector x
y = sqrt(x) %Create a vector y.

Running a script file


A script file can be executed either by typing its name in the command window and then pressing
Enter key, or directly by from the editor window by clicking on the run icon. Before this can be
done make sure that the file is saved at a particular location which is identified by MATLAB
(should be listed in current directory).
Global Variables
Global variables are the variables that once created in one part of MATLAB are recognized in
other parts of MATLAB. This is the case for variables in the command window and script files
since both operate on variables in the workspace. When a variable is defined in the command
window, it is also recognized and can be used in a script file. In the same way, if a variable is
defined in a script file it is also recognized and can be used in the command window. In other
words, once the variable is created, it exists, can be used, and can be reassigned a new value in
both the command window and the script file.
There are different types of files in MATLAB called function files that normally dont share their
variables with other parts of the program.
Input to a Script File
When a script file is executed the variables that are used in the calculations within the file must
have assigned values. The assignment of a value to a variable can be done in three ways:
1. The variable is defined and assigned value in the script file
% This script file calculates the average points scored in three games
% The assignment of the values of the points is part of the script file
Game1=75;
Game2=93;
Game3=68;

Page 2 of 7
Average_points = (Game1+Game2+Game3)/3
Save and run this file to get the output.
2. The variable is defined and assigned value in the Command Window
% This script file calculates the average points scored in three games
% The assignment of the values of the points is part of the script file
Average_points = (Game1+Game2+Game3)/3

Save the file with some file name (say game.m). In the command window:
>>Game1=75;
>>Game2=93;
>>Game3=68;
>> game

Average_points = 78.6667

Try for other values and check your results

3. The variable is defined in the script file, but a specific value is entered in the command
window when the script file is executed
This is done by using the input command to create the variable. The form of the input
command is:
variable_name=input(string with a message that is displayed in the command
window)

% This script file calculates the average points scored in three games
% The points from each game are assigned to the variables by using the input command
Game1=input(Enter the points scored in first game );
Game2= input(Enter the points scored in second game );
Game3= input(Enter the points scored in third game );
Average_points = (Game1+Game2+Game3)/3

Save the file and run it. The command window will look like this:
>>File_Name
Enter the points scored in first game 67
Enter the points scored in second game 91
Enter the points scored in third game 70

Average_points =
76
>>

Page 3 of 7
Output Commands
As discussed before, MATLAB automatically generates a display when some commands are
executed. MATLAB also has several commands that can be used to generate displays. The displays
can be messages that provide information, numerical data, and plots. The disp command displays
the output on the screen. It is used to display the elements of a variable without displaying the
name of the variable and to display text. The format of the disp command is:
disp (name of variable) or disp (text as string)
>> abc = [5 9 1;7 2 4];
>> disp(abc)
>> disp(The problem has no solution)

The next example shows the use of disp command in the script file that calculates the average
points scored in 3 games:
% This script file calculates the average points scored in three games
% the points from each game are assigned to the variables by using the input command
% The disp command is used to display the output

Game1=input(Enter the points scored in the first game);


Game2=input(Enter the points scored in the second game);
Game3=input(Enter the points scored in the third game);
Average_points=(Game1+ Game2+ Game3)/3;
disp( )
disp(The average points scored in the game is)
disp( )
disp(Average_points)

Save the command and execute it.


for Loops
In MATLAB, for loop is applied to repeat a set of commands many times. For eg: for i = 1:10
repeats the code for i = 1, 2, 3, .., 10. i print out the value of the loop counter end This ends the
section of code that is repeated.

The counter can be incremented by values other than +1.

for i=1:2:10
disp(i);
end

Page 4 of 7
This example shows that the counter variables takes on the values 1, 3, 5, 7, 9. After 9, the code
next tries i=11, but as 11 is greater than 10 (is not less than or equal to 10) it does not perform
the code for this iteration, and instead exits the for loop.

Complex structures can be made by nesting for loops within one another. The nested for loop
structure below multiplies an (m x p) matrix with a (p x n) matrix.

A = [1 2 3 4; 11 12 13 14; 21 22 23 24]; %A is 3 x 4 matrix


B = [1 2 3; 11 12 13; 21 22 23; 31 32 33]; %B is 4 x 3 matrix
im = size(A,1); %m is number of rows of A
ip = size(A,2); %p is number of columns of A
in = size(B,2); %n is number of columns of B
C = zeros(im,in); %allocate memory for m x n matrix containing
0's

Multiply the matrices

for i=1:im %iterate over each row of C


for j=1:in %iterate over each element in row
for k=1:ip %sum over elements to calculate C(i,j)
C(i,j) = C(i,j) + A(i,k)*B(k,j);
end
end
end
%C print out results of code
%A*B MATLAB's routine does the same thing

if Structure
If structures are often used in conjunction with for loops. For example, the following command
adds the components of a vector to the principal diagonal of a matrix that is the sum of two matrices
A and B.
A = [1 2 3; 4 5 6; 7 8 9];
B = [11 12 13; 14 15 16; 17 18 19];
u = [10 10 10];
C=zeros(3);
for i=1:3
for j=1:3
if(i==j)
C(i,j) = A(i,j) + B(i,j) + u(i);
else
C(i,j) = A(i,j) + B(i,j);
end
end

Page 5 of 7
end

As an alternative to if block, case structures can be used to chose among various alternatives.
for i=1:4
switch i;
case {1}
disp('i is one');
case {2}
disp('i is two');
case {3}
disp('i is three');
otherwise
disp('i is not one, two, or three');
end
end

while Loop
A while loops performs a block of code as long as the logical test expression returns a non-zero
value.
error = 283.4;
tol = 1;
factor = 0.9;
while (error > tol)
error = factor*error;
disp(error)
end
If factor >= 1, then the value of error will increase and the while loop will not terminate. A better
way, in general, to accomplish the job above is to use a for loop to place an upper limit to the
number of iterations that will be performed. A "break" command stops the iteration of the most
deeply nested for loop and is called when the condition (error < tol) is reached.
error = 283.4;
tol = 1;
factor = 0.9;
iter_max = 10000;
iflag = 0; %signifies goal not reached
for iter=1:iter_max
if(error <= tol)
iflag = 1; %signifies goal reached

Page 6 of 7
break;
end
error = factor*error;
disp(error)
end
if(iflag==0) %write message saying that goal not reached.
disp('Goal not reached');
disp(['error = ' num2str(error)]);
disp(['tol = ',num2str(tol)]);
end

Page 7 of 7

Você também pode gostar