Removing NaN Values from Array and shift left

心已入冬 提交于 2019-12-23 12:49:31

问题


I have a 34 x 1096 array that has NaN values.

 A = 
 NaN    0.2500     NaN    0.3750       NaN
 NaN    0.1100     NaN    0.4310     0.1250
 NaN    0.1250    0.2500  0.3750     0.4310

And I want

 A = 
0.2500   0.3750       NaN     NaN       NaN
0.1100   0.4310     0.1250    NaN       NaN
0.1250   0.2500     0.3750   0.4310     NaN     

Whats a simple way to do this?


回答1:


a simple way will be to use a for loop with ~isnan on each row, for example:

B=NaN(size(A));
for n=1:size(A,1)
    B(n,1:sum(~isnan(A(n,:))))=A(n,~isnan(A(n,:)));
end    

B =
0.2500    0.3750       NaN       NaN       NaN
0.1100    0.4310    0.1250       NaN       NaN
0.1250    0.2500    0.3750    0.4310       NaN

you can then assign A=B if you must... and yes this can be done without a for loop, but why bother in this case?




回答2:


[~, jj] = sort(isnan(A), 2);
B = A(bsxfun(@plus, (1:size(A,1)).', (jj-1)*size(A,1)));



回答3:


Code

 A = [
 NaN    0.2500     NaN    0.3750       NaN
 NaN    0.1100     NaN    0.4310     0.1250
 NaN    0.1250    0.2500  0.3750     0.4310]

[M,N] = size(A)
[~,col1] = sort(~isnan(A),2,'descend')

row1 = repmat(1:M,N,1)'; %%//'
restructured_indices = sub2ind(size(A),row1(:),col1(:))
A = reshape(A(restructured_indices),M,N)

Output

A =
    0.2500    0.3750       NaN       NaN       NaN
    0.1100    0.4310    0.1250       NaN       NaN
    0.1250    0.2500    0.3750    0.4310       NaN


来源:https://stackoverflow.com/questions/23225049/removing-nan-values-from-array-and-shift-left

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!