In: Computer Science
2. Vector Element Calculation Write a MATLAB script which will randomly generate a 20-element vector with integer values ranging between −100 to +100. Using LOOP command, determine the number of negative elements in the vector. For example, given A = [15 −6 0 -8 −2 5 4 −10 -3 −5], the number of negative numbers are 6.
Program:
clc;
negativeCount = 0; % Initially negative count as 0
x = randi([-100 100],1,20); # Generate random numbers between -100 to 100
fprintf("The vector elements:\n");
for(i=1:length(x)) % Loop to print vector eleemnts and count
negative elements
fprintf("%d\t",x(i)); % print vector eleemnts
if mod(i,5)==0 % mod operator print new line after 5 elements
fprintf("\n"); % print new line
end
if(x(i)<0) % check negative elements
negativeCount++; % Increment negative eleemnts count
end
end
fprintf("The number of negative elements are %d\n",negativeCount); % print negative eleemnts count
Output: