0

I have arrays like this:

[1 NaN NaN]

[NaN 2 NaN]

[NaN NaN 3]

How can I merge them to

[1 2 3]

?

3
  • You have N arrays of length N with a single number at different positions? Or is it a matrix (sorted or unsorted)? Commented Aug 2, 2016 at 23:24
  • There are actually N matrices where each row is either filled with NaN or filled with numbers. Unsorted. Commented Aug 2, 2016 at 23:27
  • And when more than one array has a non-Nan number how do we merge them? Or will there only ever by one non-Nan number per index? Commented Aug 3, 2016 at 0:51

4 Answers 4

1

Concatenate the vectors into a matrix and then compute the mean of each column discarding NaN's:

vectors = {[1 NaN NaN], [NaN 2 NaN], [NaN NaN 3]};
result = mean(vertcat(vectors{:}), 1, 'omitnan'); % or nanmean(vertcat(vectors{:}),1)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that does exactly what I was looking for. I think its simpler like this though: vectors = [[1 NaN NaN]; [NaN 2 NaN]; [NaN NaN 3]]; result = mean(vectors,'omitnan')
1

You can concatenate all the matrices into a single, big matrix and then use logical indexing to take the numbers out:

A = [1 NaN NaN 1];
B = [NaN 2 1 NaN];
C = [3 NaN 2 3];

D = [A B C];
E = D(~isnan(D))

Now E looks like this:

E =

     1     1     2     1     3     2     3

Comments

0

You can replace the NaNs with zeros:

x = [1 NaN NaN]
y = [NaN 2 NaN]
z = [NaN NaN 3]
x(isnan(x)) = 0 
y(isnan(y)) = 0 
z(isnan(z)) = 0
x + y + z 

Comments

0

You can combine all your matrices like so (this puts A on top of B):

C = [A ; B];

Then you can detect the cells that are not NaN:

D = ~isnan(C);

After that you can select with those logicals:

e = C(D);

This is now a vertical vector, you can make it horizontal with:

e = e';

2 Comments

I'm afraid ! is not valid with Matlab. You want to use ~ instead
I tested with octave, ok will change it. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.