1
votes

I have two vectors 1x5000. They consist of numbers like this:

vec1 = [NaN NaN 2 NaN NaN NaN 5 NaN 8 NaN NaN 7 NaN 5 NaN 3 NaN 4]

vec2 = [NaN 2 NaN NaN 5 NaN NaN NaN 8 NaN 1 NaN NaN NaN 5 NaN NaN NaN]

I would like to check if the order of the numbers are equal, independent of the NaNs. But I do not want to remove the NaNs (Not-a-Number) since I will use them later. So now I create a new vector and call it results. Once they come in the same order, it is correct and we fill results with 1. If the next numbers are not equal we add 0 to results.

An example results would look like this for vec1 and vec2: [1 1 1 0 1 0 0]

The first 3 numbers are the same, then 7 is compared to 1 which gives 0, then 5 compared to 5 is true which gives 1. Then the last two numbers are missing which gives 0.

One reason that I don't want to remove the NaNs is that I have a time vector 1x500 and somehow I want to get the time for each 1 and 0 (in a new vector). Is that possible too?

Help is super appreciated!

2

2 Answers

3
votes

This is how I would do it:

temp1 = vec1(~isnan(vec1));
temp2 = vec2(~isnan(vec2));
m = min(numel(temp1), numel(temp2));
M = max(numel(temp1), numel(temp2));
results = [(temp1(1:m) == temp2(1:m)), false(1,M-m)];

Note that here results is a binary array. If you need it numeric, you can convert it to double for instance.

Regarding your concern about NaNs, depends on what you want to do with your arrays. If you are going to process them, it is more convenient to remove the NaNs. In order to keep the track of things you can keep the index of the kept elements:

id1 = find(~isnan(vec1));
vec1 = vec1(id1);

vec1 =

     2     5     8     7     5     3     4

id1 =

     3     7     9    12    14    16    18

% and same for vec2

If you decide to remove the NaNs, the solution will be the same, with all temps replaced with vec.

1
votes

This would be my solution, using a mix of logical indexing and the find function. Returning the timestamps for the 1's and 0's is actually more tedious than finding the 1's and 0's.

vec1 = [NaN NaN 2 NaN NaN NaN 5 NaN 8 NaN NaN 7 NaN 5 NaN 3 NaN 4];
vec2 = [NaN 2 NaN NaN 5 NaN NaN NaN 8 NaN 1 NaN NaN NaN 5 NaN NaN NaN];
t=1:numel(vec1);

ind1=find(~isnan(vec1));
ind2=find(~isnan(vec2));
v1=vec1(ind1);
v2=vec2(ind2);
if length(v1)>length(v2)
   ibig=1; 
else
    ibig=2;
end
n=min(length(v1),length(v2));
N=max(length(v1),length(v2));
v=false(1,N);
v(1:n)=v1(1:n)==v2(1:n);

t_ones1=t(ind1(v));
t_ones2=t(ind2(v));
if ibig==1
    t_zeros1=t(ind1(~v));
    t_zeros2=t(ind2(~v(1:n)));
else
    t_zeros1=t(ind1(~v(1:n)));
    t_zeros2=t(ind2(~v));
end