part 4 is what I need help with
How do I write a set of double for loops to find and count how many times the number (n) occurs in the array you created in item 3 above. The answer can be 0. The size of the array varies so the number of random numbers varies. i.e. a 3x3 array has 9 values where a 6x6 array has 36 values which will increase the chance of some occurrences of the number.
T= 1;
while (T==1)
r = input('Enter number of rows ') ;
c= input(' Enter number of columns ');
n = input('Enter range of random 0-9 ');
disp(n);
a = uint16(rand(r,c)*n 1);
fprintf(' n = ] \n', n);
disp('Cool Matrix A');
disp(a);
b = uint16(rand(r,c)*n);
disp('Cooler Matrix B ' );
disp(b);
T= input('Enter 1 to continue \n'); end
CodePudding user response:
Taking a as your target matrix and n as your target integer to find. finding number of occurence using 2 loop can be done as below.
count=0;
size_a=size(a);
for i=1:size_a(1)
for j=1:size_a(2)
if a(i,j)==n
count=count 1;
end
end
end
But this job can be done much more simply without using for loops by substituting them with matlab's internal function find. This will save time and computation complexity
count = length(find(a==n));