简体   繁体   English

Matlab:每行或每列的第一个非零元素

[英]Matlab: First Non-zero element of each row or column

For example, 例如,

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? 如何获得每行的第一个非零元素的向量?

You can use max : 你可以使用max

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

Rows for which sel equalse zero - are all zeros and the corresponding column in c should be ignored. sel等于零的行 - 全部为零, c的相应列应该被忽略。

Result: 结果:

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

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

In order to find the first non-zero row index (for each column) you just need to apply max on the first dimension: 为了找到第一个非零行索引(对于每个列),您只需要在第一个维度上应用max

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

Here is a solution based on accumarray that will work even if a row is all zeros. 这是一个基于accumarray的解决方案,即使一行全为零也能工作。

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];

[r,c] = find(A);

%# for every row, take the minimum column index and put NaN if none is found
firstIndex = accumarray(r,c,[size(A,1),1],@min,NaN);

You can do it by executing find function for each row as follows: 您可以通过执行每行的查找功能来执行此操作,如下所示:

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];

% make cell of rows
cellOfRows = num2cell(A, 2);

% apply find function for each row
indexOfFirstNonZeroValues = cellfun(@(row) find(row, 1, 'first'), cellOfRows);


indexOfFirstNonZeroValues =

     1
     1
     3
     2
     1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM