MATLAB Answers

Store NaN and remove in for loop

70 views (last 30 days)
Essentially, I have two arrays of the same size, one contains some NaNs and I want to remove the corresponding points in the second array
I have the equation:
SOAM = nansum(CP(1:(n-3)))/sum(norm(fixed_xyz(2:n,:)-fixed_xyz(1:n-1,:)));
  • CP contains values from 0-180 with some NaN size = 100,3
  • fixed_xyz contains binary values with no Nan size = 100,3
Using "nansum" you can ignore NaNs but I want to avoid the corresponding points in the array "fixed_xyz".
for k = 1:size(CP)
if CP(k) = NaN
CP(k) = []
fixed_xyz(k) = []
Trouble with this is that the loop reduces the size of CP making the itteration of the for loop over step the actual size and an error occurs.
How can I get around this? Is there a simpler notation for this?
Cheers, Will


Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 4 Jan 2015
Edited: Stephen Cobeldick on 4 Jan 2015
There are multiple issues with your code. Here are a few that I quickly picked out:
  • using = to test for equivalency, whereas the correct code to test for equivalency is == . In MATLAB = is used only to assign a value.
  • using CP(k)=NaN to test if an element is NaN. It is important to learn that in floating point number convention NaN is not equal to anything, not even itself. To test if an element is NaN, use the function isnan .
  • defining the loop with for k=1:size(CP), which may not be giving you the range that you think it is: size(CP) will give (at minimum) a 1x2 numeric vector, which if you check the documentation for the : operator, the syntax a:[b,c] will be treated as a:b, so your code will only iterate up to the number of rows of CP.
If you want to remove all NaN elements from matrix CP, and the corresponding elments from matrix fixed_xyz, you can use MATLAB's rather powerful indexing and vectorization abilities. I would advise not removing the data, but just keeping an index to use whenever you need the data without the NaN's, something like this:
>> A = [1,2,3;4,NaN,6;NaN,NaN,9];
>> B = reshape(11:19,3,[]).';
>> X = isnan(A);
>> A(~X) % gives the elements of A without NaN's
>> B(~X) % and the corresponding ones for B.
You could even use this index within a loop, as you seem to be attempting something like this in your equation at the beginning of your question:
>> for k=1:size(A,1), B(k,~X(k,:)), end
ans =
11 12 13
ans =
14 16
ans =


William on 4 Jan 2015
Just what I was looking for. Thanks

Sign in to comment.

More Answers (0)

Sign in to answer this question.

Translated by