How to use an if statement to substitute NaN

조회 수: 10 (최근 30일)
Jonathan Gingrich
Jonathan Gingrich 2020년 6월 27일
댓글: KALYAN ACHARJYA 2020년 6월 28일
I am trying to use a combination of if and for statements to find and replace certain cells in my matrix with NaN.
My goal for this code is to develop an algorithm that looks through my final vector (in this case p4) and replaced all values in p4 with Nan when the percent difference between p1 and p2 (calculated in percdif) is greater than 10%. However, I want it to skip every cell where p4 is less than 20.
Here is my current code
%create example data
p1=[11 15 7 40 50 100];
p2=[8 14 6 38 35 95];
%Combine and take row mean
p3=[p1' p2'];
p4=mean(p3,2);
%Determine percent difference of each row
percdif=nan(size(p3,1),1);
for i=1:size(p3,1);
prep(i,1)=(p3(i,1)-p3(i,2))/p3(i,1);
end
%Determine which percent differences are greater than 10%
badpercdif=abs(percdif)>0.1;
%for all data where the p4 value is greater than 20,
%if the corresponding percdiff is greater than .1, then replace that value with NaN
This was my attempt:
cp1=p4;
for i = 1:size(cp1,1)
if cp1(i)>20
cp1(badpercdif)=NaN;
else
continue
end
end
this gives the result:
cp1=[NaN 14.5 6.5 39.0 42.5 97.5]
My intended result was
cp1=[9.5 14.5 6.5 39 NaN 97.5]
What do I need to change in my for and if loops to be able to get this result?

채택된 답변

KALYAN ACHARJYA
KALYAN ACHARJYA 2020년 6월 27일
편집: KALYAN ACHARJYA 2020년 6월 27일
p1=[11 15 7 40 50 100];
p2=[8 14 6 38 35 95];
%Combine and take row mean
p3=[p1' p2'];
p4=mean(p3,2);
%Determine percent difference of each row
percdif=nan(size(p3,1),1);
for i=1:size(p3,1);
prep(i,1)=(p3(i,1)-p3(i,2))/p3(i,1);
end
%Determine which percent differences are greater than 10%
badpercdif=abs(percdif)>0.1;
cp1=p4;
cp1(round(cp1)==43)=NaN
Please note: Here it is forcefully manipulated and here loop can be avoided.
  댓글 수: 2
Jonathan Gingrich
Jonathan Gingrich 2020년 6월 27일
Sorry, I wasn't clear on my goal.
My goal for this code is to develop an algorithm that looks through my final vector (in this case p4) and replaced all values in p4 with Nan when the percent difference between p1 and p2 (calculated in percdif) is greater than 10%. However, I want it to skip every cell where p4 is less than 20.
KALYAN ACHARJYA
KALYAN ACHARJYA 2020년 6월 28일
cp1(badpercdif & p4>20)=NaN

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by