Jackie
Jackie

Reputation: 73

insert NaNs where needed in matlab

i have the following three vectors and i want to insert NaNs into B where A misses the data points in An. So my Bn should be [0.1;0.2;0.3;NaN;NaN;0.6;0.7]. How can i get the Bn? Thanks.--Jackie

A=[1;2;3;6;7]; An=[1;2;3;4;5;6;7]; B=[0.1;0.2;0.3;0.6;0.7];

Upvotes: 0

Views: 114

Answers (1)

ShadowMan
ShadowMan

Reputation: 381

Okay so first off, you cant store the string 'NaN' into one cell of a matrix, it must be stored into a cell array. The code snip below gives you your solution, if cell array is an okay output. Please let me know any questions or concerns you might have.

Forget the italic parts, Thanks David K.

   % NaN solution for Jackie

   A=[1;2;3;6;7]; An=[1;2;3;4;5;6;7]; B=[0.1;0.2;0.3;0.6;0.7];

   len = max(length(A),length(An))
   Bn = zeros(len,1);

   k = 0; % adjust the index so that you don't call B outside of its size

   for i =1 :len
       ind= A(An(i)==A);
       if isempty(ind) ==1
       Bn(i) = nan(1,1)
       k = k+1;
       else
       Bn(i) = B(i-k)
       end
   end

Upvotes: 1

Related Questions