Reputation:
I have a n x 2 matrix in Octave, and I would like to find every row where the matrix(row, 1) and matrix(row, 2) elements are non-zero. I could use a for loop like this:
[nrows, ncols] = size(data);
for i = 1:nrows
if(data(i, 1) ~= 0 && data(i, 2) ~= 0)
% Do something
end
end
The issue with that is that n is about 3 million, and iteration in Octave takes for ever. I feel like there is a way to do it with find, but I haven't been able to figure it out yet.
Anyone have any advice?
Thanks!
Upvotes: 0
Views: 198
Reputation: 814
If performance is the issue: maybe try converting both columns to logical:
useful = and(logical(data(:,1)),logical(data(:,2)))
Then you can again use logical indexing:
filtered = data(useful,:)
Upvotes: 0
Reputation: 724
I think in this case (since it is related with zero values) the following also should work
idx=(data(:,1).*data(:,2)~=0)
But @H.Muster's solution is the one that works in all cases, hence a better one.
Upvotes: 0
Reputation: 9317
You can create use logical indexing:
idx = all(data(:,1:2)~=0, 2);
The resulting vector idx
contains 1
s in every row where both cells are non-zero and 0
otherwise.
Upvotes: 2