MATLAB Fundamentals
2.4 Program Examples
Example 2.1
% exa.m
% This program calculates e^x by series and by MATLAB’s exp( ) function.
% e^x = 1+x+x^2/2!+x^3/3!+x^4/4! +...+
% The “for loop” ends when the term only affects the seventh significant
% figure.
clear; clc;
x=5.0;
sum=1.0;
for n=1:100
term=x^n/factorial(n);
sum=sum+term;
if(abs(term) <= sum*1.0e-7) break;
end endex1=sum;
ex2=exp(x);
fprintf(‘x=%3.1f ex1=%8.5f ex2=%8.5f \n’,x,ex1,ex2);
% Note: A variable name cannot be the same as the name of a file.
% Therefore, use exa as the file name and not ex.
Example 2.2
% exB.m
% CALCULATION OF e^x WHERE x IS INPUTTED FROM THE KEYBOARD
% The function ”sum” is used to sum all the terms determined in the
% “for loop”
clear; clc;
Table 2.4 ex Series Term ndex
! ! !
I 1 2 3 4
1 2 3 4
2 3 4
ex= + +x x + x + x
fprintf(‘Calculation of e raised to a power x \n’);
x=input(‘enter a value for the exponent of e \n’);
for n=1:100
term(n)=x^n/factorial(n);
endex1=1.0+sum(term);
ex2=exp(x);
fprintf(‘x=%5.2f ex1=%10.5f ex2=%10.5f \n’,x,ex1,ex2);
Example 2.3
% while1.m
% CALCULATION OF e^5 USING A WHILE LOOP
% In this example term(n) is obtained from term (n-1) by multiplying
% term(n-1)by x and dividing by index n.
clear; clc;
x=5.0; sum=1.0; term=1.0; n=1;
while abs(term) > sum*1.0e-7 term=term*x/n;
ex=sum; disp(x); disp(ex);
Example 2.4
% matrix1.m
% INPUTTING A 3 BY 3 MATRIX FROM THE KEYBOARD
% NESTED LOOPS ARE USED clear; clc;
for n=1:3 for m=1:3
fprintf(‘n=%i m=%i ‘,n,m);
a(n,m)=input(’Enter a(n,m) ’);
fprintf(’\n’);
% ESTABLISHING A FUNCTION TO EVALUATE e^x
% In this example term(n) is obtained from term(n-1) by multiplying
% term(n-1) by x and dividing by index n.
function ex=exf(x) sum=1.0; term=1.0;
for n=1:100 term=term*x/n;
sum=sum+term;
if abs(term) <= sum*1.0e-5 break;
end
endex=sum;
% In Command Window type in
% exf(5.0) or y=exf(5.0)
Example 2.6
% table_plot.m
% This program creates a simple table and a simple plot.
% First a table of y1=n^2/10 and y2=n^3/100 is created.
% Then y1 and y2 are plotted.
clear; clc;
% By printing the output to a file, one can edit the output
% such as lining up column headings, etc. This cannot be
% done if one prints to the screen.
% Column headings
fprintf(fo,’t y1 y2 \n’);
fprintf(fo,’---\n’);
for n=1:10
fprintf(fo,’%8.1f %10.2f %10.2f \n’,t(n),y1(n),y2(n));
end
% Creating the plot, y1 is red, y2 is in green.
% Plot identification is also established by adding text to the plot;
plot(t,y1,’r’,t,y2,’g’),grid, title(‘y1 & y2 vs. t’);
% After viewing the plot, text can be entered to identify which
% curve is y1 and which curve is y2.
text(6.5,2.5,’y1’), text(4.2,2.4,’y2’);
% The data t, y1 and y2 can be saved in a data file and loaded later
% to be used in another program. By the use of the ‘clear’ command
% the data file is removed from the workspace. The load command
% brings it back into the workspace and can be used in another program.
data1=[t y1 y2];
% data1 is saved as a mat file in the working directory.
save data1;
clear;
% the clear command removes data1 from the workspace.
% Color types
% blue b
% This script is a sample of a plot program loading data obtained
% in another program clear; clc;
load data1 x=data1(:,1);
y=data1(:,2);
z=data1(:,3);
plot(x,y,’--’,x,z,’-.’);
xlabel(‘x’), ylabel(‘y,z’), title(‘y & z vs. x’), grid, text(5.4,3.4,’y’),text(7.2,3.5,’z’),
% print;
% curve types:
% solid default
% dashed -- (minus sign)
% dashed-dot -.
% doted :
% point .
% plus +
% star *
% circle 0
% x-mark x
% The point and below are points on the plot that are not connected.
A neat table can also be created by copying the output data to EXCEL. To do this, follow these steps:
1. First create the data either in a file or on the screen.
2. Highlight the data to be copied and from the menu bar, select “edit” and
“copy” from the drop-down menu list (the copy option can also be obtained by right-clicking the mouse).
3. Open the EXCEL program and click on “edit” in the menu bar. Select
“paste” from the drop-down menu list giving a single block of data.
4. Then enlarge column “A” to include the entire data set.
5. Now select “data” from the menu bar, and select “text to columns” from the drop-down menu.
6. Click on “finish,” then highlight the table area and select the “center” option in the menu bar to center the data in each column.
7. To add table headings, place the cursor in the top left margin and select
“insert” from the menu bar and “rows” from the drop-down menu.
8. Type in table headings in each column.
9. To add lines separating rows and columns, first highlight the area that is to have the separating lines, then select “format” from the menu bar and “cells”
from the drop-down menu list. Then select “border” from the “Format Cells”
page. Click on the separating lines that you wish to appear in your table.
10. To print the table, click on the print icon in the menu bar.
Example 2.8
% subplot1.m
% This program is an example of the use of the subplot command.
% Values of y1 and y2 are taken from the saved data file ‘data1’
% Separate plots of y1 vs. t & y2 vs. t are plotted on the same page.
clear; clc;
load data1;
for i=1:2
subplot(1,2,i);
if i==1
plot(t,y1), xlabel(‘t’), ylabel(‘y1’), title(‘y1 vs. t’), grid;
end if i==2
plot(t,y2), xlabel(‘t’), ylabel(‘y2’), title(‘y2 vs. t’), grid;
end end
Example 2.9
% plotg.m
% This program is a demonstration of creating a semi-log plot clc; clear;
x=1:0.5:5;
for i=1:9
y(i)=3.0*exp(x(i));
end
semilogy(x,y), title(‘semi-log plot of y & x’), xlabel(‘x’), ylabel(‘y’),grid;
Before running Example 2.10 the data file “GAUSS6.DAT” needs to be created. To do this, from the COMMAND window click on
file-Blank M-file. Type in the following data (numbers only):
8.77 2.40 5.66 1.55 1.0
Save the file as GAUSS6.DAT in the working directory.
Example 2.10
% amatrix7.m
% MATRIX A(I,J) IS READ FROM A FILE
% amatrix7.m
% MATRIX A(I,J) IS READ FROM A FILE NAMED “GAUSS6.DAT”
% NOTE: BEFORE RUNNING THIS PROGRAM THE DATA FILE GAUSS6.DAT MUST
% FIRST BE CREATED AND SAVED IN THE WORKING DIRECTORY.
clear; clc;
n=5;A=zeros(n); B=zeros(1,n);
fin=fopen(‘GAUSS6.DAT’,’r’);
fprintf(fo,’ output.dat \n’);
fprintf(fo,’ Matrix A elements \n’);
for i=1:n for j=1:n
fprintf(fo,’ %8.3f ’,A(i,j));
end
fprintf(fo,’\n’);
end
% Note that rows become columns and columns become rows.
fprintf(fo,’\n\n Matrix B elements \n’);
for i=1:n
fprintf(fo, ’ %8.3f \n’,B(i));
% The A matrix is returned to its original state.
end
fclose(fo);
C=[A’ B];
moutput(C);
This is the GAUSS6.DAT data file (this statement is not in the data file; only numbers should be in this file).
% moutput.m
% This Function is to be created with “amatrix7.m”
% This function accepts matrix A & matrix B and prints them out to
% output2.dat
function D=moutput(C) n=5;A=C(:,1:n)
B=C(:,n+1)
fo=fopen(‘output2.dat’,’w’);
fprintf(fo,’ output2.dat \n’) fprintf(fo,’ Matrix A elements \n’) for i=1:n
for j=1:n
fprintf(fo,’ %8.3f’,A(i,j));
end
fprintf(fo,’\n’);
end
fprintf(fo,’\n\nMatrix B elements \n’);
for i=1:n
fprintf(fo,’ %8.3f \n’,B(i));
end fclose(fo;
Example 2.11
% charmatrix.m
% Sometimes one might wish to print out a string of characters in a
% loop. This can be done by declaring a 2-D character string matrix as
% shown in this example. Note that all row character strings
% must have the same number of columns and that character strings must
% be enclosed by apostrophe marks.
clear; clc;
char=[‘Internal modem ’ ‘Graphics circuit board’
‘CD drive ’
‘DVD drive ’
‘Floppy drive ’ ‘Hard disk drive ’];
for i=1:5
fprintf(‘%22s \n’,char(i,1:22));
end
Example 2.12
% char1.m
% This example is a modification of Example 2.11. The program asks the
% user if he/she wishes to have the output go to the screen or to a
% file.
% This example illustrates the use of the switch statement.
clear; clc;
char=[‘Internal modem ’ ‘External modem ’ ’Graphics circuit board’
’CD drive ’
’Hard disk drive ’];
fprintf(’you have a choice, you can have the output go to the’);
fprintf(’screen or go to a file named output.dat \n’);
var=input(’enter s for screen or f for file ...
each enclosed by apostrophe mark \n’);
switch(var)
fprintf(’you did not enter an s or an f, try again \n’);
exit;
fclose(fo);
end
Example 2.13
% grades.m
% This example uses the if-elseif ladder.
% The program determines a letter grade depending on the score the user
% enters from the keyboard.
clear; clc;
gradearray=[‘A’; ‘B’; ‘C’; ‘D’; ‘F’];
score=input(‘Enter your test score \n’);
fprintf(‘score is:%i \n’,score);
if score > 100,
fprintf(‘error: score is out of range. Rerun program \n’);
break;
elseif (score >= 90 && score <= 100) grade=gradearray(1);
elseif (score >= 80 && score < 90) grade=gradearray(2);
elseif (score >= 70 && score < 80) grade=gradearray(3);
elseif (score >= 60 && score < 70) grade=gradearray(4);
elseif (score < 60) grade=gradearray(5);
end
fprintf(‘grade is:%c \n’,grade);
Example 2.14
% grades3.m
% This example uses a loop to determine the correct interval of
% interest. For a large number of intervals, this method is more
% efficient (fewer statements) than the method in Example 2.13.
% The program determines a letter grade depending on the score the user
% enters from the keyboard.
clear; clc;
gradearray=[‘A’; ‘B’; ‘C’; ‘D’; ‘F’];
sarray=[100 90 80 70 60 0];
score=input(‘Enter your test score \n’);
fprintf(‘score is:%i \n’,score);
% The following 2 statements are needed for the case when score = 100.
if score = = 100
grade=gradearray(1);
else
for i=1:5
if (score >= sarray(i+1) && score < sarray(i)) grade=gradearray(i);
end end end
fprintf(‘grade is:%c \n’,grade);
MATLAB function interp1 (the last character is a one). The format for the func-tion is
y2 = interpl ( , , )x y x2
where x,y are the set of data points and x2 is the set of x values at which the set of y2 values is to be determined by linear interpolation. Arrays x and y have to be of the same length.
Example 2.15
% interp1f.m
% This program uses MATLAB’s function interp1 to interpolate for
% specific volume of air. Air table values for specific volume (m^3/kg)
% vs. temperature (K) are given.
clear; clc;
Tt=[150 200 250 300 350 400 450 500];
vt=[0.04249 0.05665 0.07082 0.08498 0.09914 0.11330 0.12747 0.14163];
fprintf(‘This program interpolates for specific volume,v, at \n\n’);
fprintf(‘a specified temp, T. Table temperature range ...
is 150-500(K) \n\n’);
T=input(‘Enter T at which v is to be determined \n\n’);
v=interp1(Tt,vt,T);
fprintf(’ T=%6.1f (K) v=%9.5f (m^3/kg) \n’,T,v);