Add missing numbers between elements in an array
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Deepak Singh
am 11 Mai 2021
Kommentiert: Deepak Singh
am 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.
0 Kommentare
Akzeptierte Antwort
Fangjun Jiang
am 11 Mai 2021
Bearbeitet: Fangjun Jiang
am 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)
Weitere Antworten (1)
Matt J
am 11 Mai 2021
Bearbeitet: Matt J
am 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,
Var2_filled,
Siehe auch
Kategorien
Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!