MATLAB Answers

How to use an if statement to substitute NaN

6 views (last 30 days)
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?

  0 Comments

Sign in to comment.

Accepted Answer

KALYAN ACHARJYA
KALYAN ACHARJYA on 27 Jun 2020
Edited: KALYAN ACHARJYA on 27 Jun 2020
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 Comments

Jonathan Gingrich
Jonathan Gingrich on 27 Jun 2020
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.

Sign in to comment.

More Answers (0)


Translated by