Question #52519

In this part, you will use logical vectors to make multiple decisions in parallel concerning values in two arrays. Firstly, generate two random [1x10] arrays using randi. The numbers should be integers between 0 and 100. Let’s call these two arrays a1 and a2.
Your task is to generate a third array, a3, which at each index, contains the largest number out of the two earlier arrays. You must accomplish this using a logical vector and no loops.
An example snippet of code that would accomplish the same task, with a for-loop, is given below:
% For each index i, the corresponding a3
% value will be the larger of a1(i), a2(i)
for i=1:10
a3(i) = max(a1(i),a2(i));
end
Hint: try constructing a logical vector of size [1x10] to store logical values based on if a1(i) > a2(i)

Expert's answer

%generate random vector size 10 in range [0;100]

a1 = randi([0 100],10,1);

a2 = randi([0 100],10,1);

%calculate value of maximum of a1 and a2

a3=(a1>a2).*a1+(a1<=a2).*a2

## Comments

## Leave a comment