找到最后非零元素的给定矩阵的每行中的索引? [英] Find the index of the last non-zero element in each row of a given matrix?

查看:283
本文介绍了找到最后非零元素的给定矩阵的每行中的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于任意大小的矩阵 X ,我怎么找到最后一个非零元素的给定矩阵的每一行中的索引?

For an arbitrary sized matrix x, how do I find the index of the last non-zero element in each row of a given matrix?

例如,对于基体

x = [ 0 9 7 0 0 0; 5 0 0 6 0 3; 0 0 0 0 0 0; 8 0 4 2 1 0 ]

向量 [3 6 0 5] 应该得到的。

推荐答案

下面是一个较短的版本,结合找到 accumarray

Here's a shorter version, combining find and accumarray

x = [ 0 9 7 0 0 0; 5 0 0 6 0 3; 0 0 0 0 0 0; 8 0 4 2 1 0 ];
%# get the row and column indices for x
[rowIdx,colIdx] = find(x);
%# with accumarray take the maximum column index for every row
v = accumarray(rowIdx,colIdx,[],@max)'
v =
     3   6   0   5

这篇关于找到最后非零元素的给定矩阵的每行中的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆