find negative numbers in a matrix in matlab

You can use a nested loop to iterate over each element in the matrix, and use a conditional statement to check if the element is negative. Here's an example code block:

main.m
% Define a matrix
A = [1 -2 3; -4 5 -6; 7 -8 9];

% Get the size of the matrix
[row, col] = size(A);

% Initialize a vector to store the negative numbers
neg_nums = [];

% Iterate over each element in the matrix
for i = 1:row
    for j = 1:col
        % Check if the element is negative
        if A(i,j) < 0
            % Add the negative number to the vector
            neg_nums(end+1) = A(i,j);
        end
    end
end

% Display the negative numbers
disp(neg_nums);
471 chars
23 lines

In this example, we define a 3x3 matrix A. We then use the size function to get the number of rows and columns in A, and use a nested loop to iterate over each element in the matrix. We use the conditional statement if A(i,j) < 0 to check if the current element is negative, and if it is, we add it to the neg_nums vector using neg_nums(end+1) = A(i,j). Finally, we display the contents of the neg_nums vector using the disp function.

gistlibby LogSnag