Info

此问题已关闭。 请重新打开它进行编辑或回答。

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

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

the cyclist
the cyclist 2020-2-24
编辑:the cyclist 2020-2-24
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.

Walter Roberson
Walter Roberson 2020-2-24
编辑:Walter Roberson 2020-2-24
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.

Community Treasure Hunt

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

Start Hunting!

Translated by