Add missing numbers between elements in an array

3 vues (au cours des 30 derniers jours)
Deepak Singh
Deepak Singh le 11 Mai 2021
Commenté : Deepak Singh le 12 Mai 2021
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.

Réponse acceptée

Fangjun Jiang
Fangjun Jiang le 11 Mai 2021
Modifié(e) : Fangjun Jiang le 11 Mai 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)

Plus de réponses (1)

Matt J
Matt J le 11 Mai 2021
Modifié(e) : Matt J le 11 Mai 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
  1 commentaire
Deepak Singh
Deepak Singh le 12 Mai 2021
Thanks. It workred too. I just accepted the one before.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by