I have a matrix z (say 200x5) where only one element is non-zero in each row. What would be the most efficient way of finding that index without using for loops.
For example:
z=[1 0 0;0 0 1];
a=findRow(z)
where a should display:
[1 3]
Turns out that 'find' is the solution, except that I have to transpose z:
[rowidx,~]=find(z');
edit: Have to transpose it first because matlab finds things column first. 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:
z = sparse([1,0,0;0,0,1]);
You can still just use find
to get your answer
[~,idx] = find(z);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.