Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

MATLABLoopingExercise and Solution

The document provides a series of MATLAB programming tasks involving vector operations, random number generation, and array manipulations. It includes commands to compute sums, create random arrays, and implement loops to track conditions based on random numbers. Additionally, it discusses methods for calculating specific array values and averages based on random inputs.

Uploaded by

ngọc nguyễn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

MATLABLoopingExercise and Solution

The document provides a series of MATLAB programming tasks involving vector operations, random number generation, and array manipulations. It includes commands to compute sums, create random arrays, and implement loops to track conditions based on random numbers. Additionally, it discusses methods for calculating specific array values and averages based on random inputs.

Uploaded by

ngọc nguyễn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

1.

Given the vector x = [1 8 3 9 0 1], create a short set of commands that will

a. Add up the values of the elements (Check with sum.)


b. Computes the running sum (for element j, the running sum is the sum of the
elements from 1 to j, inclusive. Check with cumsum.)

% Given vector x

x = [1 8 3 9 0 1];

% a. Add up the values of the elements

sum_result = sum(x);

disp(['Sum of elements: ' num2str(sum_result)]);

% b. Computes the running sum

running_sum = cumsum(x);

disp('Running sum:');

disp(running_sum);

2. Create an M-by-N array of random numbers (use rand). Move through the array,
element by element, and set any value that is less than 0.2 to the value 0 and any value
that is greater than or equal to 0.2 to the value 1.
3. Given x = [4 1 6] and y = [6 2 7], compute the following arrays

a. aij = xiyj
b. bij = xi/yj
c. ci = xiyi, then add up the elements of c.
d. dij = xi/(2 + xi + yj)
e. eij = reciprocal of the lesser of xi and yj

Array e:

>> disp(e);
0.2500 0.5000 0.2500

1.0000 1.0000 1.0000

0.1667 0.5000 0.1667

>>

4. Write a script that will use the random-number generator rand to determine
the following:

a. The number of random numbers it takes to add up to 20 (or more).


b. The number of random numbers it takes before a number between 0.8 and 0.85
occurs.
c. The number of random numbers it takes before the mean of those numbers is
within 0.01 of 0.5 (the mean of this random-number generator).

It will be worthwhile to run your script several times because you are dealing with random
numbers. Can you predict any of the results that are described above?

Solution
1. x = [1 8 3 9 0 1]

a. total = 0;
for j = 1:length(x)
total = total + x(j);
end
b. runningTotal = zeros(size(x));
runningTotal(1) = x(1);
for j = 2:length(x)
runningTotal(j) = runningTotal(j-1) + x(j);
end

2. A = rand(4,7);
[M,N] = size(A);
for j = 1:M
for k = 1:N
if A(j,k) < 0.2
A(j,k) = 0;
else
A(j,k) = 1;
end
end
end

3. x = [4 1 6], y = [6 2 7]
N = length(x);
for j = 1:N
c(j) = x(j)*y(j);
for k = 1:N
a(j,k) = x(j)*y(k);
b(j,k) = x(j)/y(k);
d(j,k) = x(j)/(2 + x(j) + y(k));
e(j,k) = 1/min(x(j),y(k));
end
end
c = sum(c); % or use 1.a. loop

4. These code snippets do the job but their repeated use is much
more interesting. An example is given for the first exercise.

a. total = 0; % initialize current sum (the test variable)


count = 0; % initialize the counter (output of the
program)
while total < 20 % loop until 20 is exceeded
count = count + 1; % another loop repeat => another number added
x = rand;
total = total + x; % modify the test variable!
end
disp(['It took ',int2str(count),' numbers this time.'])

------------------------------------------------------------

To do this many times, place the above code in a for-loop.


Some simple (though perhaps subtle) changes are needed wth respect
to retaining the counts for each repeat. Also, the summary has
been changed from a single text message to a histogram.

Nrep = 1000; % collect 1000 repeats of the above code


count = zeros(Nrep,1);
for j = 1:Nrep
total = 0; % reset the test variable each repeat!!!
while total < 20
count(j) = count(j) + 1; % use a vector to capture each result
total = total + rand;
end
end
hist(count,min(count):max(count))
xlabel('Number of random numbers from U(0,1) added to make 20')
ylabel('Count')
title(['Histogram of results for ',int2str(Nrep),' repeats'])

------------------------------------------------------------

b. count = 0;
while 1 % infinite loop use
count = count + 1;
x = rand; % get a number
if (x < 0.85) & (x > 0.8) % check the value
break % break out if in selected range
end
end
disp(['It took ',int2str(count),' numbers this time.'])

c. count = 0;
avg = 0; % test variable
while abs(avg - 0.5) > 0.01
count = count + 1;

% The following line is one way to update the average.


% (count-1)*avg is the sum of the first count-1 numbers
% and rand just adds another number. Dividing by count
% then gives the new average.

avg = ((count-1)*avg + rand)/count; % modify the test var.

% There are other ways to do this and you are encouraged


% to come up with them

end
disp(['It took ',int2str(count),' numbers this time.'])

You might also like