Add missing numbers between elements in an array

3 views (last 30 days)
I have two array like this
Var1= [1 1 2 4 5 7 7 7 8 10 11 13 14 14 17 17 17 17 18 20];
Var2= [0.5 0.3 0.1 0.6 0.2 0.4 0.8 0.9 0.3 0.2 0.1 0.4 0.8 0.7 0.5 0.9 0.2 0.8 0.3 0.7];
I want to fill in missing serial numbers in Var1 without compromising the other values. I want my Var1 to look like this:
Var1_filled=[1 1 2 3 4 5 6 7 7 7 8 9 10 11 12 13 14 14 15 16 17 17 17 17 18 19 20];
For Var2 I want to use a fill in value like NaN for corresponding missing numbers in Var1. So Var2 should look this this:
Var2_filled= [0.5 0.3 0.1 NaN 0.6 0.2 NaN 0.4 0.8 0.9 0.3 NaN 0.2 0.1 NaN 0.4 0.8 0.7 NaN NaN 0.5 0.9 0.2 0.8 0.3 NaN 0.7];
So, when I make
plot(Var1_filled,Var2_filled)
then I can visualize the missing points.
I can't do this manually because I have tons of data so I need some automatic way to do this. That way I can put this in loop and run through all my data. Any help would be appreciated.

Accepted Answer

Fangjun Jiang
Fangjun Jiang on 11 May 2021
Edited: Fangjun Jiang on 11 May 2021
%%
Var1= [1 1 2 4 5 7 7 7 8 10 11 13 14 14 17 17 17 17 18 20];
Var2= [0.5 0.3 0.1 0.6 0.2 0.4 0.8 0.9 0.3 0.2 0.1 0.4 0.8 0.7 0.5 0.9 0.2 0.8 0.3 0.7];
x=min(Var1):1:max(Var1);
NewEle1=setdiff(x,Var1);
NewEle2=nan(size(NewEle1));
NewVar1=[Var1,NewEle1];
NewVar2=[Var2,NewEle2];
[NewVar1,index]=sort(NewVar1);
NewVar2=NewVar2(index)

More Answers (1)

Matt J
Matt J on 11 May 2021
Edited: Matt J on 11 May 2021
Var1= [1 1 2 4 5 7 7 7 8 10 11 13 14 14 17 17 17 17 18 20];
Var2= [0.5 0.3 0.1 0.6 0.2 0.4 0.8 0.9 0.3 0.2 0.1 0.4 0.8 0.7 0.5 0.9 0.2 0.8 0.3 0.7];
a= accumarray(Var1(:),1);
b=a>0;
a(a==0)=1;
c=repelem(b,a).';
Var1_filled=repelem(1:numel(Var1),a);
Var2_filled=nan(size(c));
Var2_filled(c)=Var2;
Var1_filled,
Var1_filled = 1×27
1 1 2 3 4 5 6 7 7 7 8 9 10 11 12 13 14 14 15 16 17 17 17 17 18 19 20
Var2_filled,
Var2_filled = 1×27
0.5000 0.3000 0.1000 NaN 0.6000 0.2000 NaN 0.4000 0.8000 0.9000 0.3000 NaN 0.2000 0.1000 NaN 0.4000 0.8000 0.7000 NaN NaN 0.5000 0.9000 0.2000 0.8000 0.3000 NaN 0.7000

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!