Matlab:每行或每列的第一个非零元素 [英] Matlab: First Non-zero element of each row or column

查看:543
本文介绍了Matlab:每行或每列的第一个非零元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如

A = [ -1   0  -2   0   0
   2   8   0   1   0
   0   0   3   0  -2
   0  -3   2   0   0
   1   2   0   0  -4];

如何获取每行的第一个非零元素的向量?

how can I get a vector of the first nonzero elements of each row?

推荐答案

您可以使用max:

>> [sel, c] = max( A ~=0, [], 2 );

sel等于零的行-全部为零,并且c中的相应列应被忽略.

Rows for which sel equalse zero - are all zeros and the corresponding column in c should be ignored.

结果:

>> [sel c]= max( A~=0, [], 2 )

sel =
 1
 1
 1
 1
 1
c =
 1
 1
 3
 2
 1

为了找到第一个非零行索引(针对每一列),您只需要在第一个维度上应用max:

In order to find the first non-zero row index (for each column) you just need to apply max on the first dimension:

>> [sel r] = max( A~=0, [], 1 );

这篇关于Matlab:每行或每列的第一个非零元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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