In: Computer Science
PART 3 – Using logical vectors and logical 2D arrays
In this part, you will use a logical vector to make multiple decisions in parallel concerning values in two arrays. Firstly, generate two random [1x12] arrays using randi. The numbers should be integers between 1 and 5. Let’s call these two arrays a1 and a2. Your task is to generate a third array, a3, which at each index, contains a true/false value that defines whether the values in arrays a1 and a2 are NOT equal (use ~=). Now use the a3 array to obtain those values in a1 and a2 that are equal. You must accomplish all this using the logical vector and no loops.
Finally, create a random 5x5 numeric 2D array with numbers between 1 and 100 using one line of code. Replace all values divisible by 3 in this matrix with the value -1, again, using only one line of code.
% Matlab script to use logical vector and arrays
% generate two random [1x12] arrays using randi.
a1 = randi([1,5],1,12);
a2 = randi([1,5],1,12);
fprintf('a1 : ');
disp(a1);
fprintf('a2 : ');
disp(a2);
% generate a third array, a3, which at each index,
% contains a true/false value that defines whether
% the values in arrays a1 and a2 are NOT equal (use ~=).
a3 = (a1~=a2);
fprintf('a3 : ');
disp(a3);
% a1(a3==0)) returns the values from those indices in a1 where a3
is 0 i.e
% false (which means values at those indices in a1 and a2 are
equal))
fprintf('a1 = a2 : ');
disp(a1(a3==0));
% create a random 5x5 numeric 2D array with numbers between 1
and 100
a = randi([1,100],5,5);
fprintf('a :\n');
disp(a);
%Replace all values divisible by 3 in this matrix with the value -1
a(mod(a,3) == 0) = -1;
fprintf('Modified a :\n');
disp(a);
%end of script
Output: