Efficiently finding non zero numbers from a large matrix

半世苍凉 提交于 2021-01-29 02:19:11

问题


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)?


回答1:


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


来源:https://stackoverflow.com/questions/28930002/efficiently-finding-non-zero-numbers-from-a-large-matrix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!