Moving NaN elements from the last columns to the first column, iteratively

4 ビュー (過去 30 日間)
gd94
gd94 2019 年 6 月 10 日
コメント済み: TADA 2019 年 6 月 11 日
Hello community,
I'm struggling to figure out a way to automatize a problem I'm confronting on Matlab. Here is a fictitious matrix that replicates my issue (mine is much bigger, but always has between 0 and 2 NaN observations at the end of the matrix):
A = [1 2 3 4 5 6 7 8 NaN NaN;
1 2 3 4 5 6 7 8 9 NaN;
1 2 3 4 5 6 7 8 9 10]
For those rows that have NaNs, I want to move the NaN observations to the front of the matrix, so as to have this;
A = [NaN NaN 1 2 3 4 5 6 7 8;
NaN 1 2 3 4 5 6 7 8 9;
1 2 3 4 5 6 7 8 9 10]
This is a code which works for me with a row vector (i.e A = [1 2 3 4 5 6 7 8 NaN NaN]):
while isnan(A(end))
A = A(1:end-1);
A = [NaN,A];
end
I can't seem to figure out how to broaden the loop to the general case presented above (the 3x10 matrix).
Thank you!

採用された回答

TADA
TADA 2019 年 6 月 10 日
編集済み: TADA 2019 年 6 月 11 日
The simplest way would be to loop through the rows:
i = isnan(A);
for j = 1:size(A,1)
A(j,:) = [A(j,i(j,:)) A(j,~i(j,:))];
end
Another approach:
a1 = A';
[~, ord] = sort(~isnan(a1));
ord2 = ord + repmat(0:size(a1,1):numel(a1)-1, size(a1,1),1);
a2 = a1(ord2)'
  3 件のコメント
gd94
gd94 2019 年 6 月 11 日
Works.... great! Thank you so much TADA
TADA
TADA 2019 年 6 月 11 日
cheers no problem

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

その他の回答 (1 件)

Bob Thompson
Bob Thompson 2019 年 6 月 10 日
Do you want your numeric values in ascending order? If so you should be able to do the following:
A = sort(A,2,'MissingPlacement','first');
  1 件のコメント
gd94
gd94 2019 年 6 月 11 日
No, not necessarily. The 1 2 3 ..... 9 were just examples of numbers, but they need not be in ascending order. The order should just be maintained when moving the NaNs to the front.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by