Reputation: 354
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?
Upvotes: 4
Views: 282
Reputation: 221574
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
Upvotes: 1
Reputation: 112689
[~, jj] = sort(isnan(A), 2);
B = A(bsxfun(@plus, (1:size(A,1)).', (jj-1)*size(A,1)));
Upvotes: 2
Reputation: 26069
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?
Upvotes: 1