Biomedical Engineering Reference
In-Depth Information
case 3
plot(theta,sin(3*theta)./exp(-theta));
end
can be inserted as the block following the case 's'. The
complete MATLAB script for this exercise is:
twopi ¼ 2*pi;
theta ¼ 0 : (twopi/100):twopi;
letter ¼ input ('Please enter either s
or c: ') ;
col ¼ input ('Please enter either 1, 2
or 3: ') ;
figure (1) ;
switch letter
case 's'
switch col
case 1
plot (theta, sin (theta));
case 2
plot (theta,exp(-theta).* (sin
(theta) ).^2);
case 3
plot (theta, sin (3* theta)./ exp
(-theta) );
end
case 'c'
switch col
case 1
plot (theta, cos (theta) ) ;
case 2
plot (theta, cos (2* theta) . / exp
(-2* theta) );
case 3
plot (theta, exp (-theta) .* (cos
(theta) ).^3);
end
end
A sample session using this script is below, and the re-
sults are shown in Fig. 2.1b-3 . Why does the plot
function use the scale from 0 to 7 for the independent
variable?
0.35
0.3
0.25
0.2
0.15
0.1
0.05
0
0
1
2
3
4
5
6
7
Figure 2.1b-3
Example 2.1b.4 The use of while loops.
Write a script that computes the number of random
numbers required to add up to 20 (or more). You are to
use the random-number generator rand in this exercise.
Solution
The random number generator in MATLAB returns
a pseudo-random number that is uniformly distributed
between 0 and 1.We refer to it as a pseudo-randomnumber
because the sequence of numbers generated depend on the
state of the computer random number generator at
the time that the function call is made. For example, the
following call to the random number generator
>> rand
ans ¼
0.9501
returns the result shown. The randomnumber returned can
be equal to or greater than zero, but is strictly less than 1.
The MATLAB script should stop executing once the
sum of all the random numbers generated reaches 20.
This means that the script will continue to repeat gen-
erating random numbers, adding each new one to the
running sum, until the sum reaches at least 20. You also
have to count the number of random numbers generated.
Since it is not possible to predict exactly how many
numbers need to be added, the program will have to
repeat generating random numbers, until the condition is
satisfied. The MATLAB while.end construct will be
used to control the repetition.
The algorithm for solving this problem is:
1. The running sum of random numbers must start at
0 before the random numbers are generated. Set the
count to be zero.
2. Check to see if the sum is greater than or equal to 20.
If it is, then stop this script. If the sum is less than 20,
then go to step 3.
Please enter either s or c: 's'
Please enter either 1, 2 or 3: 2
2.1b.3.3 Iteration
2.1b.3.3.1 While loops
Repetition is where a sequence of instructions, or block, is
repeated until a condition is satisfied. The condition can be
expressed in terms of state of the data or an external input.
A generic repetition structure is a while.do loop.
Search WWH ::




Custom Search