Info

Cette question est clôturée. Rouvrir pour modifier ou répondre.

What is the best practice of conditional statements in solving a complicatedly branched system?

1 vue (au cours des 30 derniers jours)
Phú Ngô
Phú Ngô le 24 Fév 2020
Clôturé : MATLAB Answer Bot le 20 Août 2021
Hi,
My problem is best described using pictures:
pH Table
My goal is to achieve the value of f(pH), which is determined by using the equations in the right column. But it is constricted by 2 variables, the temperature and pH, which are the given input. If the temperature is between the given value on the table (for example: Temperature = 30oC), f(pH) is linearly interpolated. My first thought was using if statement, it was easy to use but it would be 20+ if statements.
What is your best practice in solving this problem?
Thank you and best regards.
  2 commentaires
darova
darova le 24 Fév 2020
You have only a few function the same. The rest are all different. So if..else statement is ok in this case
I think you should use it
Phú Ngô
Phú Ngô le 25 Fév 2020
Thanks a lot! That is really helpful of you!

Réponses (2)

the cyclist
the cyclist le 24 Fév 2020
Modifié(e) : the cyclist le 24 Fév 2020
An alternative would be to build up your expression via logical components of this form
a = 2.0676;
b = -0.2309;
c = 4.342
f = (T==5) .* (pH >= 3.5 && pH < 4.6) .* (a + b*pH) ...
+ (T==5) .* (pH >= 4.6 && pH < 6.5) .* (c - (etc etc)) ...
+ (T==10) .* (etc etc)
+ etc etc
Only the line that meets all the appropriate conditions will contribute to the value of f.
I think it is debatable that this is "better" than using if-else expressions, though.
  2 commentaires
Phú Ngô
Phú Ngô le 25 Fév 2020
Big thank to the two of you! I appreciate all your useful tips and tricks!

Walter Roberson
Walter Roberson le 24 Fév 2020
Modifié(e) : Walter Roberson le 24 Fév 2020
Another alternative is to discretize() based upon the pH, with edges at 3.8, 4.3, 4.57, 4.6, and so on.
Then for each temperature, have a look-up table of the coefficients to use for each of the bins. In cases where the bin edges were more finely divided than required for the temperature, you would just repeat the same coefficients for each section that woudl be treated the same.
The entries are all polynomials of degree 3 or less, except for one of the entries at 80 and one at 90, which are A*exp(-b*pH) format. Those could be included in the general framework by using an additional two coefficients that are set to 0 for the other cases, and for those two cases, the polynomial terms would be set to 0 while the exponential terms were not. The value from the exponential term being added to the value calculated by the polynomial terms.
  1 commentaire
Phú Ngô
Phú Ngô le 26 Fév 2020
Thanks! That was extremly helpful. I will look up to the function and attempt to apply it to my code.

Community Treasure Hunt

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

Start Hunting!

Translated by