- https://www.mathworks.com/help/matlab/ref/nnz.html
- https://www.mathworks.com/help/matlab/ref/randi.html?s_tid=doc_ta#buf2dpy-7
I think this is vectorizing
    3 views (last 30 days)
  
       Show older comments
    
    Spaceman
 on 8 Apr 2024
  
    
    
    
    
    Commented: Spaceman
 on 9 Apr 2024
            Given: Write a code that prompts user to enter a number of rows and columns. Create a matrix, with the provided size that has random integers between -10 and 10.
Find: How do I have MATLAB individually look at each value in the matrix and determine if the value is negative, and if it is, add one to a variable used to keep track of the negative values? (Otherwise do nothing). Then display to the user the number of negative values in the matrix.
Issue: I am running into syntax error brain. In my head this code works, but it's not what MATLAB thinks is right.
My solution: Once I figure out how to get my random numbers to properly generate I can tackle the tracking system... I might be going about this all wrong, though.
R=input('Enter the number of rows: ');
C=input('Enter the number of columns: ');
MAT=[R(randi([-10,10]),C(randi([-10,10])))]; % Getting an error here, syntax?
for x=1:R<1
    disp('Negative')
        for y=1:C<1
            disp('Negative')
        end
end
% Then create a variable neg and somehow??? do neg=neg+1 every time there is a
% negative value found in the above for loop.
0 Comments
Accepted Answer
  Venkat Siddarth Reddy
      
 on 8 Apr 2024
        Hi Kyle,
In the above code you are trying to use the variables "R" and "C" as the functions to create a matrix of  dimensions of R and C. However, these are not functions but variables with user-defined values.
To create a matrix of random numbers of above dimensions you can pass the dimension values to the "randi" function itself. 
%Let the values of R,C be 3,4
R=3;
C=4;
MAT= randi([-10 10],R,C)
And to find the count of negative numbers.You can either loop through each element of the matrix and check for the value or you can apply a boolean matrix operations and count for all the valid elements. Following example shows both the methods
%Method-1 Iterate through each element
negCount=0;
for i=1:R
    for j=1:C
        if(MAT(i,j)<0)
            negCount=negCount+1;
        end
    end
end
negCount
%Method-2 Matrix boolean operation
%Generating a boolean matrix on condition whether the element is less than zero or not. 
negCount=nnz(MAT<0)  %nnz - gives number of non zero elements in the matrix.
To learn more about randi with these arguments and nnz function, refer to the following documentation:
I hope it helps!.
More Answers (0)
See Also
Categories
				Find more on Creating and Concatenating Matrices in Help Center and File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
