MATLAB PROGRAMMING
SCRIPT FILE
Disadvantage of Commands in the command
window
- it can not be saved
- it can not be executed again
- it is not interactive
- every time the enter key is pressed only the last command is
executed.
- everything executed before is unchanged
- if a change or correction is needed in a command that was previously
executed and the results of 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 the file. It is
called a script file
About Script Files
• A script file is a sequence of MATLAB commands, also called a
program.
• 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.
• When a script file has a command that generates an output, the
output is displayed in the command window.
• Using a script file is convenient because it can be edited and
executed many times.
• Script files can be edited in any text editor and then pasted in the
MATLAB editor.
Creating and Saving a Script File
Script files are created and edited in the Editor/Debugger Window. This window is
opened from the Command window. In the File menu, select New and the
select M-file. An open Editor/Debugger Window is shown
The commands in the script file are typed line by line. The commands
can also be typed in any text editor or word processor program and
then copied and pasted in the Editor/Debugger window.
Before a script file can be executed it has to be saved. The rules for
naming a script file follow the rules of naming variable. The names
of user-defined variables, predefined variables, MATLAB commands
or functions should not be used to name a script files.
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 from the editor
window by clicking on the Run icon.
In order to run a file, the file must either be in the current directory or in
the search path.
The current directory is shown in the “Current Directory” field in the
desktop toolbar of the Command Window. It can be changed either
in the Current directory window or by typing cd command in the
Command Window (type cd space then the name of the directory
followed by a colon).
Search Path
When MATLAB is asked to run a script file or to execute a function, it searches
for the file in directories that are listed in the search path. The directories that are
included in the search path are displayed in the Set Path Window that can be
opened by selecting Set Path in the File menu. Once the set path is opened, new
folders can be added to or removed from, the search path
Input to a Script File
1. The variable is defined and assigned value in the script file – the assignment of the
variable is part of the script file.
example1:
%This script file calculates the value of X1, X2,X3.
%The assignment of the values is part of the script file.
A=[3 5 2
082
6 2 8]
B=[8;-7;26]
C=A\B
create a folder in drive C named examplematlab. save the file as example1scriptfile to drive
C.
2. The variable is defined and assigned value in the Command Window.
example:2
%This script file calculates the value of X1, X2,X3.
%The assignment of the values is part of the script file.
%Matrices A & B are done in the Command Window
C=A\B
save the file as example2scriptfile to folder examplematlab.
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.
variable_name=input(‘string with a message that is displayed in the Command
Window’)
The string is displayed in the command window when the script file runs. Type
the value and press enter key.
The input command can also be used to assign a string to a variable.
variable_name=input(‘prompt message’,’s’)
‘s’ defines the character that will be entered as a string.
example3:
%This script file calculates the value of X1, X2,X3.
%The elements of matrices A and B are assigned to variables by
%using the input command.
A=input(‘Enter the elements of Matrix A’)
B=input(‘Enter the elements of Matrix B’)
C=A\B
save the file as example3scriptfile to folder examplematlab.
Output Commands
The disp Command – it is used to display the elements of a variable without displaying the
name of the variable, and to display text.
disp(name of a variable) or disp(‘text as string’)
example4: the display command is used to display the output.
% 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 ‘);
ave_points=(game1+game2+game3)/3;
disp(‘’)
disp(‘The average of points scored in a game is:’)
disp(‘’)
disp(ave_points)
save the file as example4scriptfile to examplematlab.
To display output in a table, first define a variable that is an array with
the numbers and then use the disp command to display the array.
example5:
yr=[1984 1986 1988 1990 1992];
pop=[127 130 136 145 158];
tableYP(:,1)=yr’;
tableYP(:,2)=pop’;
disp(‘ YEAR POPULATION’)
disp(‘ (millions)’)
disp(‘’)
disp(tableYP)
save the file as example5scriptfile to folder examplematlab.
The fprintf Command
The fprintf command can be used to display output (text and data) on the
screen or to save it to a file. With this command the output can be
formatted.
fprintf command to display text:
fprintf(‘text typed in as a string’)
it is possible to start a new line in the middle of the string. This is done by
inserting \n (escape character) before the character that will start the new
line.
example6:
fprintf(‘The problem, as entered has no solution. Please check the input data.’)
x=6;d=19+5*x;
fprintf(‘Try to run the program later.’)
y=d+x;
fprintf(‘Use different input values.’)
save it as example6scriptfile to folder example matlab
fprintf command to display a mix of text and numerical data.
fprintf(‘text as string %-5.2f additional text’,variable_name)
The % sign marks the spot where the number is inserted within the text.
- flag (optional) (- left justifies the number within the field, + prints a
sign character (+or-) in front of the number, 0 adds zeros if the
number is shorter that the field.
5.2 field width and precision (optional)
f conversion character (required)
conversion characters:
e Exponential notation using lower case e
E Exponential notation using upper case E
f fixed point notation
g the shorter of e or f notations
G the shorter of E of f notations
i interger
example7:
% This script file calculates the average points scored in three games.
%The values are assigned to the variables by using the input command.
%The fprintf command is used to display the output.
game(1)=input(‘Enter the points scored in the first game ‘);
game(2)=input(‘Enter the points scored in the second game ‘);
game(3)=input(‘Enter the points scored in the third game ‘);
ave_points=mean(game);
fprintf(‘Average of %f points was scored in the three
games.’,ave_points)
save it as example7scriptfile to folder examplematlab
It is also possible to insert more than one number within the text.
fprintf(‘text text %g text text %f text text %f’)
The fprintf command is vectorized. This means that when a variable that
is a vector or a matrix is included in the command, the command
repeats itself until all the elements are displayed. If the variable is a
matrix the data is used column by column.
example8:
x=1:5;
y=sqrt(x);
T=[x;y]
fprintf(‘If the number is:%i, its square root is:%f\n’,T)
save it as example8scriptfile to folder examplematlab in drive C.
ACTIVITY 1
• The figure below shows a circuit with seven resistors connected in series.
• Write a program in a script file that calculates the voltage across each resistor, and
the power dissipated in each resistor. When the script file is executed it requests
the user to first enter the source voltage and then to enter the resistance of the
resistors in a vector. The program displays a table with the resistances listed in the
first column, the voltage across the resistor in the second, and the power
dissipated in the resistor in the third column. Display headings for the columns.
• Following the table, the program displays the current in the circuit, and the total
power. Use fprintf command for this part of the program.
• Hint: Use the voltage divider principle.
• Run the file and enter the following data for Vs and R’s.
Vs=24V, R1=20, R2=14, R3=12, R4=18, R5=8, R6=15, R7=10
ACTIVITY 2
• The figure below shows a transistor circuit. Write
a program in a script file that calculates the DC
base, collector and emitter currents and the DC
base, collector and emitter voltages with reference
to ground. When the script file is executed it
requests the user to first enter the source voltage
and then to enter the value of the resistors and the
beta. The program displays a table with the
terminal currents in the first column and the
voltages in the second. In the column, arrange the
results from base, to collector to emitter. Display
headings for the columns.
• Run the file and enter the data needed, including
the value of =50.
• Note: use format short e command for your
answers.