Академический Документы
Профессиональный Документы
Культура Документы
SO
SOLVING
G WITH MATLAB
A A
AND MAPLE
MODULE 3
PROGRAMMING
2017
1. M Files
M files allow you to save multiple MATLAB commands in a file and
M-files
then run them with a single command or mouse click. While you may
have solved the simple problem above correctly on the first try, more
complicated problems generally require some trial and error –
running, editing, and re-running a series of commands several times.
While the Command History Window can be useful during the first
stages of this process, eventually you will find it more efficient to use
M fil M-files
M-files. M fil also
l allow
ll you to
t share
h your solution
l ti tot a problem
bl
with other MATLAB users, and to format your results for others to
read There are two different kinds of M
read. M-files:
files: script M
M-files
files and
function M-files.
M-files are ordinaryy text files containingg MATLAB commands. You
can create and modify them using any text editor or word processor
that is capable of saving files as plain ASCII text. (Such text editors
i l d Notepadd and
include d WordPad
d d ini Windows,
i d and
d emacs and d vii in
i
2
UNIX.) MATLAB
You can also use the File menu or the two leftmost icons on the tool
bar to start the Editor/Debugger, either to create a new M
M-file
file or to
open an existing M-file. Double-clicking on an M-file in the Current
Directory Browser will also open it in the Editor/Debugger.
2. Script M files
A script
i M-file
fil contains
i a sequence off MATLAB commands d to be
b
run in order. We now show how to construct a script M-file to solve
the mathematical problem.
problem Create a file containing the following
lines:
a=2 Save this file with the name p
program1.m
g in y
your
b=3 current directory, or in any other directory in
c=4 your path. You can name the file any way you
sum=a+b+c lik (subject
like ( bj to the
h usuall naming
i restrictions
i i on
your operating system), but the “.m” suffix is
mandatory
mandatory.
3
MATLAB
You can tell MATLAB to run (or execute) this script by typing
program1 in the Command Window. (You must not type the “.m” .m
extension here; MATLAB automatically adds it when searching for
M-files.) The output – but not the commands that produce them –
will be displayed in the Command Window. Now the sequence of
commands can easily be changed by modifying the M-file
program1 m
program1.m.
3. Addingg Comments
It is worthwhile to include comments in M-files. These comments
might explain what is being done in the calculation, or might
interpret the results of the calculation. In MATLAB, the percent sign
(%) begins a comment; the rest of the line is not executed by
MATLAB.
MATLAB
4
MATLAB
4. Initializing Script M-files
In order for the results of a script M
M-file
file to be reproducible, the script
should be self-contained, unaffected by other variables that you
might have defined elsewhere in the MATLAB session, and
uncorrupted by leftover graphics.
With this in mind, you can type the line clear all at the beginning of
the script to ensure that previous definitions of variables do not affect
the results. You can also type close all at the beginning of a script M-
fil that
file th t creates
t graphics,
hi to t close
l all
ll figure
fi windows
i d and
d start
t t with
ith a
clean slate.
5 Function
5. F ti M files
fil
Function M-files, unlike script M-files, allow you to specify input
values when you run them from the MATLAB command line or from
another M-file. Like a script M-file, a function M-file is a plain text
file that should reside in your current directory or elsewhere in your
MATLAB path. 5
MATLAB
The first line of the file starts with function, which identifies the file
as a function M-file. (The Editor/Debugger colors this special word
blue.) The first line of the M-file specifies the name of the function
and describes both its input arguments (or parameters) and its output
values.
l
The file name ((without the .m extension)) and the function name
should match.
6
MATLAB
6. Taking Input from the User
When the input command is executed as the script file runs, runs the
string is displayed in the Command Window. The string is a message
prompting the user to enter a value that is assigned to the variable.
The user types the value and presses the ENTER key.
a= input('Enter the first number ');
b=input('Enter the second number ');
c=input('Enter the third number ');
sum a+b+c
sum=a+b+c
7. Displaying Output
The disp command is used to display a variable without displaying
the name of the variable and to display text.
disp(‘The Sum is ');
disp(sum)
disp( [’The sum is ’, num2str(sum)] );
7
MATLAB
The fprintf command can be used to display output (text and data) on
the screen or save it to a file. With this command (unlike with the
disp command) the output can be formatted. Text and numeral
values of variables can be intermixed and displayed in the same line.
fprintf('The sum of %g, %g and %g is %g\n',a,b,c,sum)
Step 1
Before data can be written to a file, the file must be opened. This is
done with the fopen command,
command which creates a new file or opens an
existing file. The fopen command has the form
''r'' O
Open file
fil for
f readingdi (default).
(d f lt)
‘w' Open file for writing. If the file already exists, its content is
deleted If the file does not exist,
deleted. exist a new file is created.
created
‘a' Same as ' w' , except that if the file exists the written data is
appended to the end of the file. file
'r+' Open (do not create) file for reading and writing.
‘ +' Open
‘w+' O fil for
file f readingdi andd writing. iti If the
th file
fil already
l d exists,
i t its
it
content is deleted. If the file does not exist, a new file is
created.
created
‘a+' Same as ‘w+’, except that if the file exists the written data is
appended
appe ded to tthee eendd oof tthee file.
e.
10
MATLAB
Step 2
Once the file is open, the fprintf command can be used to write
output to the file. The fprintf command is used in exactly the same
way as it is used to display output in the Command Window, except
that the variable fid is inserted inside the command. The fprintf
command then has the form:
Step 3
When the writing of data to the file is complete, the file is closed
using the fclose command.
command The fclose command has the form:
11
MATLAB
clear all
clc
P 40;Q 60;
P=40;Q=60;
theta=25:5:50;
R=sqrt(P^2+Q^2-2*P*Q*cosd(theta));
TBL=[theta;R];
fid=fopen('Resultant.doc','w');
fprintf(fid,'Variation of Resultant \n')
fprintf(fid,'Theta(in degree) Resultant (in N) \n')
fprintf(fid,'%g \t\t\t\t %8.2f\n',TBL)
fclose(fid)
9. Publishing an M-File
MATLAB comes with a very convenient command called publish
to convert a script M-file to a readable document. The default output
f
format, which
hi h we have
h f d works
found k best,
b i HTML (i.e.,
is (i a webb
page).
12
MATLAB
10. Relational and Logical Operators
A relational
l ti l operator
t compares two
t numbers
b b finding
by fi di whether
h th a
comparison statement is true or false. A logical operator examines
true/false statements and produces a result which is true or false
according to the specific operator. Relational and logical operators
are used in mathematical expressions and also in combination with
other commands, to make decision that control the flow a computer
program.
13
MATLAB
14
MATLAB
11. For- end Loops
In for-end
for end loops the execution of a command,
command or a group of
commands, is repeated for a predetermined number of items.
Example
Write a program to display the message “You are Unsuccessful” if
percentage obtained is less than 40 and “You are Successful” if
percentage obtained is greater than 40.
17
MATLAB
% exmample for if
a input('Enter your percentage:
a=input('Enter ');
if a<40
disp('You
disp( You are unsuccessful
unsuccessful'))
else
disp ('You are successful')
end
18
MATLAB
14. if- else- end Structures
Example
E ample
Write a program to display the division:
<40: Fail 40-60:
40 60: Second 60-80:
60 80: First >80: Distinction
19
MATLAB
% exmample for if else
a=input('Enter your percentage: ');
if (a<40) & (a>0)
disp('You are Fail')
else if(a<60) & (a>=40)
disp ('You are pass with SECOND DIVISION')
else if(a<80) & (a>=60)
disp
p (('You are p
pass with FIRST DIVISION')
)
else if(a<=100) & (a>60)
disp ('You are pass with DISTINCTION')
else
disp('Enter the Proper Value')
end
end
end
end
20
MATLAB
15. switch- case Structures
switch case executes certain statements based on the value of
switch-
a variable or expression.
21
MATLAB
n=input('Enter the day number: ');
switch n;
case 1
disp('Sunday')
case 2
disp('Monday')
case 3
disp('Tuesday')
case 4
disp('Wednesday')
case 5
disp( Thrusday )
disp('Thrusday')
case 6
disp('Friday')
case 7
disp('Saturday')
otherwise
disp('Not Valid')
22
end MATLAB
16. switch/case using Menu
The menu function is often used in conjunction with a switch/case
structure. This function causes a menu box to appear on the screen,
with a series of buttons defined by the programmer.
switch pr
case 1
disp('no seats remaining')
case 2
disp('2 seats remaining')
case 3
disp('5 seats remaining')
case 4
disp('10 seats remaining')
end 23
MATLAB