Non Zero element appear first with keeping the same size of the matrix?

1 回表示 (過去 30 日間)
Rubel Ahmed
Rubel Ahmed 2019 年 11 月 5 日
コメント済み: Rubel Ahmed 2019 年 11 月 5 日
A = [1 0 2 3;2 0 0 5; 3 0 0 1; 0 0 1 5];
How The matrix will be transformed like this (No-zero element will come first, row wise)
A = [1 2 3 0; 2 5 0 0; 3 1 0 0; 1 5 0 0]

採用された回答

JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH 2019 年 11 月 5 日
solution :
A = [1 0 2 3;2 0 0 5; 3 0 0 1; 0 0 1 5];
A(A==0)=nan;
A=sort(A,2);
A(isnan(A))=0;
disp(A)
  2 件のコメント
Richard Brown
Richard Brown 2019 年 11 月 5 日
This doesn't reproduce the example of the OP - it sorts the rows
Rubel Ahmed
Rubel Ahmed 2019 年 11 月 5 日
Thanks David,It works

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

その他の回答 (1 件)

Richard Brown
Richard Brown 2019 年 11 月 5 日
here's a really naive way to do it:
[m, n] = size(A);
for i = 1:m
k = find(A(i, :))
A(i, :) = [A(i, k), zeros(1, n - numel(k))]
end
I'm sure there's a more fancy vectorised method, but this will do the job.
  2 件のコメント
Richard Brown
Richard Brown 2019 年 11 月 5 日
(note this method retains the order of the elements in each row)
Rubel Ahmed
Rubel Ahmed 2019 年 11 月 5 日
Thanks @Richard Brown

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

カテゴリ

Help Center および File ExchangeDates and Time についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by