use*_*990 8 matlab matrix sparse-array sparse-matrix
例如,
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];
Run Code Online (Sandbox Code Playgroud)
如何获得每行的第一个非零元素的向量?
Sha*_*hai 17
你可以使用max:
>> [sel, c] = max( A ~=0, [], 2 );
Run Code Online (Sandbox Code Playgroud)
sel等于零的行- 全部为零,并且c应忽略相应的列.
结果:
>> [sel c]= max( A~=0, [], 2 )
sel =
1
1
1
1
1
c =
1
1
3
2
1
Run Code Online (Sandbox Code Playgroud)
为了找到第一个非零行索引(对于每个列),您只需要max在第一个维度上应用:
>> [sel r] = max( A~=0, [], 1 );
Run Code Online (Sandbox Code Playgroud)
这是一个基于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);
Run Code Online (Sandbox Code Playgroud)
您可以通过对每一行执行find函数来完成此操作,如下所示:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12755 次 |
| 最近记录: |