フィルターのクリア

how to remove zeros from the matrix?

108 ビュー (過去 30 日間)
Junseob Kim
Junseob Kim 2019 年 11 月 25 日
コメント済み: Junseob Kim 2019 年 11 月 25 日
Hello, I want to remove zero values from the matrix and cut the last elements of odd rows. For example, if I have a matrix
A=[1, 0, 2, 0, 3 ;
0, 4, 0, 5, 0 ;
6, 0, 7, 0, 8]
and, I want to make matrix like
B=[1, 2;
4, 5;
6, 7]
Please answer this question. Thanks!
  5 件のコメント
James Tursa
James Tursa 2019 年 11 月 25 日
Is it always the checkerboard pattern shown?
Junseob Kim
Junseob Kim 2019 年 11 月 25 日
Yes it is.

サインインしてコメントする。

採用された回答

the cyclist
the cyclist 2019 年 11 月 25 日
編集済み: the cyclist 2019 年 11 月 25 日
I think this does what you want:
% Replicate A into B
B = A;
% For the even-numbered rows, circularly shift the elements
B(2:2:end,:) = circshift(B(2:2:end,:),-1,2);
% Remove any columnn with a zero
B(:,any(B==0)) = [];
  1 件のコメント
Junseob Kim
Junseob Kim 2019 年 11 月 25 日
Thank you so much!!

サインインしてコメントする。

その他の回答 (3 件)

Guillaume
Guillaume 2019 年 11 月 25 日
A=[1, 0, 2, 0, 3 ;
0, 4, 0, 5, 0 ;
6, 0, 7, 0, 8];
B = reshape(nonzeros(A(:, 1:end-1).'), [], size(A, 1)).'
  1 件のコメント
Junseob Kim
Junseob Kim 2019 年 11 月 25 日
Thank you so much!!

サインインしてコメントする。


Adam Danz
Adam Danz 2019 年 11 月 25 日
This approach extracts the first two non-zero elements per row. If there are no two non-zero elements in each row an error is thrown.
A=[
1, 0, 2, 0, 3 ;
0, 4, 0, 5, 0 ;
6, 0, 7, 0, 8];
B=[1, 2;
4, 5;
6, 7];
% Number of non-zeros per row or A
numNonZeros = sum(A~=0,2);
% Replace the non-zeros after the 2nd non-zero in
% each row with 0s
A(cumsum(A~=0,2) > 2) = 0;
% Confirm that we end up with 2 non-0s in each row
if (unique(sum(A~=0,2))>0) ~= true
error('Assumption violation: the number of non-zeros in each row of A is unexpected.')
end
A = A.';
B = reshape(A(A~=0),2,size(A,2)).';
  1 件のコメント
Junseob Kim
Junseob Kim 2019 年 11 月 25 日
Thank you so much!!

サインインしてコメントする。


Kaspar Bachmann
Kaspar Bachmann 2019 年 11 月 25 日
編集済み: Kaspar Bachmann 2019 年 11 月 25 日
A=[1, 0, 2, 0, 3 ; 0, 4, 0, 5, 0 ; 6, 0, 7, 0, 8]
Var = A;
Var(:,length(Var)) = [];
for i = 1:size(Var,1)
t = Var(i,:);
idx = find(t>0);
B(i,:) = t(idx);
end
Its a bit messy, but it should work.
  1 件のコメント
Junseob Kim
Junseob Kim 2019 年 11 月 25 日
Thank you so much!!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by