Performing calculation with multiple conditions with for loop and nested if statements

I have a column of data (temperatures) and want to create a second column based on these temperatures. In Excel, it is accomplished with a simple nested if statement. My loop in Matlab, however, works for a few rows, then begins to return 0's. The conditions are:
  • If temperature (T1) is < 0, then RHCrit = 0
  • If T1 is between 0 and 20, then RHCrit = -0.00267*(T1^3)+0.160*(T1^2)-3.13*T1+100
  • If T1 is >20, then RHCrit = 80
My code right now is:
RHcrit = zeros(size(T1));
for i = 1:length(T1)
if T1(i)>0
if T1(i)<20
RHcrit(i)=-0.00267*(T1(i)^3)+0.160*(T1(i)^2)-3.13*T1(i)+100
else
RHcrit(i)=80
end
else
RHcrit(i)=0
end
end

2 commentaires

Please share the value of T1 so that your code can be tested.
Hi Nicolas,
Apologies, a .txt file is attached.

Connectez-vous pour commenter.

 Réponse acceptée

This code is working fine. Are your sure you loaded T1 properly? As KSSV mentioned, you do not need a for loop to do this calculation. Using logical indexing would be more efficient.
ds = datastore('T1.txt');
data = ds.readall();
T1 = data{:,1};
RHcrit = zeros(size(T1));
for i = 1:length(T1)
if T1(i)>0
if T1(i)<20
RHcrit(i)=-0.00267*(T1(i)^3)+0.160*(T1(i)^2)-3.13*T1(i)+100;
else
RHcrit(i)=80;
end
else
RHcrit(i)=0;
end
end

3 commentaires

Thanks for your response. I am bringing in my data a bit differently (it's not simply a text file with 1 column of data, I have dozens of columns across multiple files). I ran your code and it works fine, so it would appear that the loop is not the issue - I will examine how I am loading my data into Matlab.
I ran KSSV's code and it didn't return the correct values. It appears that the calculation for the 0<T1<20 condition was ignored.
Okay, I think there was a bug with my original file. I copied the file retrieval portion and appended the for loop, in a new file, and it worked fine. Something was wrong with the original file I was working in.
I am an idiot. I didn't add semicolons to the statements in my for/if loops. This was what was causing all of my problems.

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by