Creating a new matrix with rows from a past matrix.

4 views (last 30 days)
I have huge Nx3 matrix. I want to find all the rows with a number less then 0 in column 3 and remove them from the matrix and create a new matrix with the rows and columns i removed.
find(A(:,3) < 0) gives me the row numbers, how do i transfer them into a new matrix?

Answers (2)

madhan ravi
madhan ravi on 31 Oct 2018
idx=find(all(A(:,3) < 0))
A(idx,:)=[] %removes row
A(:,idx)=[] %removes column

Cam Salzberger
Cam Salzberger on 31 Oct 2018
Hello Oscar,
find is a fine and dandy function, but actually needs to be used far less often than many people think. The reason is that the input into find is a logical array already, which can be used to index into the array you used to build it.
So if you have your Nx3 array, A, you can get an Nx3 logical array that tells you which values are greater than or equal to 3 with this:
A >= 0
But you only care about the third column values. So you can get an Nx1 logical array by just looking at the third column, like so:
A(:, 3) >= 0
Now you can choose to only keep the rows in which the value above is true like so:
A(A(:, 3) >= 0, :)
or more clearly:
rowsToKeep = A(:, 3) >= 0;
A(rowsToKeep, :)
And if you want it assigned to a new matrix, just do:
B = A(A(:, 3) >= 0, :);
Here is one place you can get more information on logical indexing (near the bottom of the page, but the whole page has good information).
-Cam

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!