フィルターのクリア

removing zeros from matrix

1 回表示 (過去 30 日間)
Mahmoud Zeydabadinezhad
Mahmoud Zeydabadinezhad 2016 年 3 月 17 日
コメント済み: Image Analyst 2016 年 3 月 18 日
Hi,
I have a matrix like this:
0 0 2 3 4 0;
1 0 2 0 0 1;
3 2 1 0 0 0;
0 1 0 3 0 1;
I want to remove the zeros so I could have something like this:
2 3 4;
1 2 1;
3 2 1;
1 3 1;
The number of zeros in each row of the original matrix is the same. Any idea how can I do this? Commands like A=A(A ~= 0) didn't work.
Thanks!

採用された回答

Roger Stafford
Roger Stafford 2016 年 3 月 17 日
A = A.';
A = reshape(A(A~=0),3,4).';
  2 件のコメント
Mahmoud Zeydabadinezhad
Mahmoud Zeydabadinezhad 2016 年 3 月 18 日
Hi Roger, Can you please elaborate how did you come up with this solution? and what is A. ?
Thank you!
Image Analyst
Image Analyst 2016 年 3 月 18 日
Take it a step at a time and use intermediate variables and get rid of the semicolons so the result goes to the command window:
A=[0 0 2 3 4 0; 1 0 2 0 0 1; 3 2 1 0 0 0; 0 1 0 3 0 1]
Atransposed = A.'
vectorNoZeros = Atransposed(Atransposed ~= 0)
reshapedVector = reshape(vectorNoZeros,3,4).'
You'll see this, which hopefully explains it well enough:
A =
0 0 2 3 4 0
1 0 2 0 0 1
3 2 1 0 0 0
0 1 0 3 0 1
Atransposed =
0 1 3 0
0 0 2 1
2 2 1 0
3 0 0 3
4 0 0 0
0 1 0 1
vectorNoZeros =
2
3
4
1
2
1
3
2
1
1
3
1
reshapedVector =
2 3 4
1 2 1
3 2 1
1 3 1

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

その他の回答 (2 件)

Azzi Abdelmalek
Azzi Abdelmalek 2016 年 3 月 17 日
v=[0 0 2 3 4 0; 1 0 2 0 0 1; 3 2 1 0 0 0; 0 1 0 3 0 1]
out=reshape(v(v~=0),size(v,1),[])

Image Analyst
Image Analyst 2016 年 3 月 17 日
This works:
A=[0 0 2 3 4 0; 1 0 2 0 0 1; 3 2 1 0 0 0; 0 1 0 3 0 1]
for row = 1 : size(A, 1)
thisRow = A(row,:)
% Remove zeros
thisRow(thisRow == 0) = [];
% Append to new matrix.
if row == 1
Anozeros = thisRow
else
Anozeros = [Anozeros; thisRow];
end
end
A = Anozeros
I'm sure there are other ways too. (Hopefully it's not homework, though it looks like it.)
  1 件のコメント
Mahmoud Zeydabadinezhad
Mahmoud Zeydabadinezhad 2016 年 3 月 18 日
No worries. It's not a homework!

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

カテゴリ

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