Matlab Programs
Matlab Programs
Program 2
Write a program which reads a student marks in a test and then prints whether
he is passed or failed.
Solution:
We simply compare the marks with 35 in the if expression. If it is true we will
write disp( )to display "Passed" else "Failed".
The MATLAB program is shown below.
%Scriptfile: result .m
This program determines whether a student passed or failed
%Illustration of if/else
%Define variables
&mark --- student marks
%Pronpt the user for marks of a student
mark=input ( Enter student marks:);
i f marks>=35
disp('Passed');
else
disp(Failed') ;
end
Program 2
n is the product of consecutive integers from 1to n.
The factorialof an integer
That is,
factorial n=n!=n x (n-1) x (n-2) X * X1
the factorial for any given n.
Write a MATLAB program to compute
Solution:
%Scriptfile:n_factorial
factorial n
8Programe to compute
integer: ') ;
n=input ('Enter positive
factorial=1; %initialize
8Illustration of for loop
%go from 1 to n
for k=1 :n
factorial =factorial*k; &multiply 1 by 2, 3, 4, etc.
end
factorial) ;
fprintf ('%3d! =%d\n',n,
the file. For this simply
Nowexecute the above program to saving and naming
press F5 function key.
>>n factorialJ
Enter positive integer : 12
12!=479001600
>>n factorialJ
(RADIANCE PUBLISHERS)
Program 1
Write a script file to plotthe function y= x for the range of values for x from 0
to 100, with an increment of 5.
Solution :
%Program to plot the curve y=x
x=0:5:100 create vector x
y=x; %calculate y
plot (x, y) %plot x vs .y
When you run the file, MATLAB displays the following plot.
100
90
80
70
60
50
40
30
20
10
0 10 20 30 40 50 60 70 80 90 100
Fig. 12.10
Program 2
AWrite a script file to plot the curve y=x*, - 100 < x< 100.
Solution :
%Program to plot the curve y=x^2
X=-100:20: 100;
y=x. ^2 ;
plot (x, y)
When you run the file, MATLAB displays the following plot.
10000
9000
8000
7000 -
6000
5000
4000
3000
2000
1000
0 20 40 60 80 100
-100 -80 -60 40 -20
Fig. 12.11