[英]Find non-zero row index
I have a matrix z (say 200x5) where only one element is non-zero in each row.我有一个矩阵 z(比如 200x5),其中每行只有一个元素是非零的。 What would be the most efficient way of finding that index without using for loops.在不使用 for 循环的情况下找到该索引的最有效方法是什么。
For example:例如:
z=[1 0 0;0 0 1];
a=findRow(z)
where a should display: a 应该在哪里显示:
[1 3]
Turns out that 'find' is the solution, except that I have to transpose z:原来'find'是解决方案,除了我必须转置z:
[rowidx,~]=find(z');
edit: Have to transpose it first because matlab finds things column first.编辑:必须先转置它,因为 matlab 首先找到事物列。 Therefore the order of row indices is off if you don't transpose.因此,如果不转置,行索引的顺序将关闭。
If you have a matrix with mostly 0
elements, you could consider usingsparse
matrices which are designed to be spatially efficient in such cases:如果您有一个主要包含0
元素的矩阵,您可以考虑使用设计为在这种情况下具有空间效率的sparse
矩阵:
z = sparse([1,0,0;0,0,1]);
You can still just use find
to get your answer您仍然可以使用find
来获得答案
[~,idx] = find(z);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.