Add missing numbers between elements in an array
조회 수: 2 (최근 30일)
이전 댓글 표시
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
채택된 답변
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
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,
Var2_filled,
참고 항목
카테고리
Help Center 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!