MATLABLoopingExercise and Solution
MATLABLoopingExercise and Solution
Given the vector x = [1 8 3 9 0 1], create a short set of commands that will
% Given vector x
x = [1 8 3 9 0 1];
sum_result = sum(x);
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
>>
4. Write a script that will use the random-number generator rand to determine
the following:
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.
------------------------------------------------------------
------------------------------------------------------------
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;
end
disp(['It took ',int2str(count),' numbers this time.'])