To find the negative elements in a matrix in Matlab, you can use the find
command along with the logical indexing. The following code snippet shows how to do it:
main.m210 chars10 lines
The first step is to use the logical indexing to extract the negative elements from the matrix. We use the comparison operator <
to check if an element is negative or not. The result is a logical matrix of the same size as that of the input matrix A
.
In the second step, we use the find
command to find the indices of the negative elements in the matrix. The find
command returns two output vectors row
and col
corresponding to the row and column indices of the negative elements. The third output negative_elements
is a vector that contains the negative elements in the matrix.
Note that the find
command returns the indices of the elements in the matrix in a linear fashion. If you want to get the row-column indices of the negative elements, you need to use ind2sub
command.
gistlibby LogSnag