簡體   English   中英

將矩陣轉換為堆疊向量,其中每行的最后一個非零值之后的所有零都被移除

[英]Transform a matrix to a stacked vector where all zeroes after the last non-zero value per row are removed

我有一個矩陣,我想要擦除一些零值。

a=[ 1 2 3 0 0; 1 0 1 3 2; 0 1 2 5 0]

>>a =

 1     2     3     0     0
 1     0     1     3     2
 0     1     2     5     0

但是,我想只擦除每行的最后一個非零值之后的那些。 這意味着我想從第一行保留1 2 3從第二行保留1 2 3 1 0 1 3 2 ,從第三行保留0 1 2 5

我想將剩余的值存儲在向量中。 在示例的情況下,這將導致向量

b=[1 2 3 1 0 1 3 2 0 1 2 5]

我想出的唯一方法涉及一個我想避免的for循環:

b=[];
for ii=1:size(a,1)
    l=max(find(a(ii,:)));
    b=[b a(ii,1:l)];
end

有沒有辦法對這段代碼進行矢量化?

有很多可能的方法可以做到這一點,這是我的方法:

 arotate = a' %//rotate the matrix a by 90 degrees
 b=flipud(arotate)  %//flips the matrix up and down
 c= flipud(cumsum(b,1)) %//cumulative sum the matrix rows -and then flip it back.
 arotate(c==0)=[] 

 arotate =

  1     2     3     1     0     1     3     2     0     1     2     5

=========================編輯=====================

剛剛實現了cumsum可以有方向參數所以這應該做:

 arotate = a'
 b = cumsum(arotate,1,'reverse')
 arotate(b==0)=[] 

此方向參數在我的2010b版本上不可用,但如果您使用的是2013a或更高版本,則應該在那里。

這是使用bsxfun的屏蔽功能的方法 -

M = size(a,2); %// Save size parameter
at = a.'; %// Transpose input array, to be used for masked extraction

%// Index IDs of last non-zero for each row when looking from right side
[~,idx] = max(fliplr(a~=0),[],2);

%// Create a mask of elements that are to be picked up in a
%// transposed version of the input array using BSXFUN's broadcasting
out = at(bsxfun(@le,(1:M)',M+1-idx'))

示例運行(以顯示掩碼使用情況) -

>> a
a =
     1     2     3     0     0
     1     0     1     3     2
     0     1     2     5     0
>> M = size(a,2);
>> at = a.'; 
>> [~,idx] = max(fliplr(a~=0),[],2);
>> bsxfun(@le,(1:M)',M+1-idx') %// mask to be used on transposed version
ans =
     1     1     1
     1     1     1
     1     1     1
     0     1     1
     0     1     0
>> at(bsxfun(@le,(1:M)',M+1-idx')).'
ans =
     1     2     3     1     0     1     3     2     0     1     2     5

暫無
暫無

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

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