Add missing numbers between elements in an array

조회 수: 4 (최근 30일)
Deepak Singh
Deepak Singh 2021년 5월 11일
댓글: Deepak Singh 2021년 5월 12일
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.

채택된 답변

Fangjun Jiang
Fangjun Jiang 2021년 5월 11일
편집: Fangjun Jiang 2021년 5월 11일
%%
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)

추가 답변 (1개)

Matt J
Matt J 2021년 5월 11일
편집: Matt J 2021년 5월 11일
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
Deepak Singh
Deepak Singh 2021년 5월 12일
Thanks. It workred too. I just accepted the one before.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by