簡體   English   中英

在矩陣中找到第一個非零列

[英]finding the first non zero column in a matrix

如果我有如下的矩陣A

2 0 0 0 0 0 
3 0 0 0 0 0
4 0 0 0 0 0
7 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0 
0 0 0 0 0 0  

所有其他列始終為零

我想得到數組B = [7 4 3 2]

我怎樣才能做到這一點 ?

嘿,這是我能想到的用於獲取所有非零元素的最簡單的代碼:

test_matrix = [ 2, 0 , 0 ,0 ,0;...
    3, 0 , 0 ,0 ,0;...
    4, 0 , 0 ,0 ,0;...
    7, 0 , 0 ,0 ,0;...
    0, 0 , 0 ,0 ,0;...
    0, 0 , 0 ,0 ,0;...
    0, 0 , 0 ,0 ,0];

B = test_matrix(test_matrix ~= 0) %//rowwise non zeroelements

輸出是一列,我們需要對其進行轉置然后翻轉。 如果將4的位置更改為該列中的另一個插槽,它將顯示在輸出數組B的末尾。如果要將最后一個非零元素作為第一個輸出,則可以轉置數組:

B=fliplr(B'); %//fliping first to last and so in ( for the transpose array)

如果您希望列按順序排列,即使如上所述4不在數組中的其他位置,請使用轉置矩陣:

helper= test_matrix' %//(')transposing Matrix
C = helper(helper ~=0) %//Columnwise non zero-elements

如果每列有一個以上的非零元素,則必須檢查是否要按行或按列列出它們:檢查B和C的定義。 顯然,C不是反序的,只能使用

 C=fliplr(C); %%//flipping first to last and so on

希望這可以解釋您遇到的所有問題。
結果:

test_matrix = [ 2, 0 , 0 ,0 ,0;...
    3, 0 , 0 ,0 ,0;...
    0, 0 , 4 ,0 ,0;...
    7, 0 , 0 ,0 ,0;...
    0, 0 , 0 ,0 ,0;...
    0, 0 , 0 ,0 ,0;...
    0, 0 , 0 ,0 ,0];

helper= sum(test_matrix');
C = helper(helper ~=0);
B = test_matrix(test_matrix ~= 0);

結果是:

C= (7,4,3,2);
B= (4,7,3,2);

您可以遍歷各列並使用find 讓我們來

M =
     0     0     1     0     0
     0     0     2     0     0
     0     0     3     0     0
     0     0     4     0     0
     0     0     0     0     0

作為我們的示例矩陣。

for i = 1:size(M,2)
    ind = find(M(:,i));
    if ind
        found = ind;
        break;
    end
end

會得到你

found = 
    1
    2
    3
    4

可以翻轉的

found = found([end:-1:1])'

這會讓你

found =
    4 3 2 1

您的問題尚不清楚,但這似乎可以滿足您的要求(因為所有其他列均為零):

flipud(nonzeros(A))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM