How to use an if statement to substitute NaN

7 次查看(过去 30 天)
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.

请先登录,再进行评论。

更多回答(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