How to use an if statement to substitute NaN

10 visualizaciones (últimos 30 días)
Jonathan Gingrich
Jonathan Gingrich el 27 de Jun. de 2020
Comentada: KALYAN ACHARJYA el 28 de Jun. de 2020
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?

Respuesta aceptada

KALYAN ACHARJYA
KALYAN ACHARJYA el 27 de Jun. de 2020
Editada: KALYAN ACHARJYA el 27 de Jun. de 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 comentarios
Jonathan Gingrich
Jonathan Gingrich el 27 de Jun. de 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.
KALYAN ACHARJYA
KALYAN ACHARJYA el 28 de Jun. de 2020
cp1(badpercdif & p4>20)=NaN

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by