# For loop in a function (not getting right results)

3 ビュー (過去 30 日間)
Alexander Guillen 2022 年 3 月 18 日

I created the function Antoine to not bother solving the equation over and over. However, when I call the function in a for loop I dont get the right answers compared to the way i would do it in excel. I would appreciate any help.   p1_pure (using matlab) =
0 0 0 0 0.9800
using excel:
1.903628223
2.09045263
2.283986537
2.483798717
2.689463014

サインインしてコメントする。

### 採用された回答

Voss 2022 年 3 月 18 日
Several things. First:
for i = length(T_K)
should be
for i = 1:length(T_K)
The first way just iterates once, using the last element of T_K, which is why the first four elements of p1_pure are zero.
Second: T_K in the code is in Kelvin, but T in the formula is in Celsius, so you would have to use T_K-273.15 in your MATLAB calculation to convert it.
Third: exp() is natural (base e) exponentiation, but the formula says log10 (not natural log), so your MATLAB code would have 10^() rather than exp().
Making those changes still doesn't give a result that matches what Excel gives you, so I would check the units of a, b and c, and check your Excel formula.
a = 4.00266;
b = 1171.53;
c = -48.784;
T_K = 300:10:340;
for i = 1:length(T_K)
p1_pure(i) = 10^(a-b/(T_K(i)-273.15+c)); % make this a function if you want
end
p1_pure
p1_pure = 1×5
1.0e+102 * 0.0000 1.4794 Inf 0.0000 0.0000
##### 2 件のコメント表示非表示 1 件の古いコメント
Voss 2022 年 3 月 18 日

You're welcome! And nope, log10() and exp() (or log()) are not interchangeable:
• exp() is the inverse function of log(), both of which have to do with the base e (i.e., natural) logarithm, also known as ln() in math (but not in MATLAB).
• 10^() is the inverse function of log10(), which have to do with the base-10 logarithm.
• There is also log2(), whose inverse function would be 2^() (or pow2()).

サインインしてコメントする。

### カテゴリ

Find more on Loops and Conditional Statements in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!