sounak mohanta
sounak mohanta

Reputation: 19

Efficiently finding non zero numbers from a large matrix

I have a 512 x 512 x 112 matrix with three kind of values : zeroes, non zeroes and NaN.

How can I get the indices of the non zero values of the matrix efficiently (without using loop)?

Upvotes: 1

Views: 79

Answers (1)

chepyle
chepyle

Reputation: 996

The comment from @scmg is the way to go- Matlab's linear logical indexing is a way to avoid looping over the elements; it only takes 1.2 sec on my PC. Here is a working example:

rng(8675309) %jenny number for consistency
x=randn([512,512,112]); % make random matrix
x(x<0)=NaN; % set some elements to NaN
x(x<4)=0; % set some elements to zero
[i1,i2,i3]=ind2sub(size(x),find(x>0)); %use find+ind2sub to avoid loop
scatter3(i1,i2,i3)% plot results for fun

Upvotes: 2

Related Questions