Greetings!
I am new to MATLAB and going in circles trying to logic my way what should be a simple function:
How do I calculate, using a "for" loop, x^k?
My function inputs are ( x, n ); I start with:
% code
ExpValue = 0;
k = 1;
for i = 1:n;
ExpValue = ExpValue + ?
end
Recall that I must use a Sum for the exponential function... x*1, x*x, x*x*x all the way to squaring x up to n times.
Thanks!

 採用された回答

Roger Stafford
Roger Stafford 2016 年 4 月 9 日
編集済み: Roger Stafford 2016 年 4 月 9 日

1 投票

Trying to compute x^n using only summation is a terrible method. Surely you would be allowed to use multiplication!
ExpValue = 1;
for k = 1:n % (Corrected)
ExpValue = ExpValue*x;
end

4 件のコメント

Dillan Masellas
Dillan Masellas 2016 年 4 月 9 日
Thanks! So I've successfully implemented this code - not sure how I didn't see the simplicity.
Now, I am trying to simulate e^x using sum(x^k/k!). I can't use the factorial function, so I'm getting around that by using prod(1:k) where k=1 and k=k+1 in the for loop.
However, the number just grows with the iteration rather than converging on exp(x).
Thoughts?
Roger Stafford
Roger Stafford 2016 年 4 月 9 日
You should realize that the number of terms needed in that series to get the desired accuracy depends on the size of x. For large values of x you will need to compute a very large number of terms. Eventually when the factorial n in the denominator sufficiently exceeds x^n, you can quit, but not before that. For example, with x = 10 and n = 20, the value of x^20/20! is 41.1, so you're not done yet with that summation.
Actually this series is only practical for small values of x, say smaller than about 4 or 5. For larger values of x you can take advantage of the fact that exp(a+b) = exp(a)*exp(b) and derive the values of exp(x) in terms of exp for smaller arguments. For example, exp(10.1234) = exp(1)^10*exp(0.1234).
This doesn't work for fractional case
n = 10.2
n = 10.2000
x = 2.5;
x ^ n
ans = 1.1455e+04
ExpValue = 1;
for k = 1:n % (Corrected)
ExpValue = ExpValue*x;
end
ExpValue
ExpValue = 9.5367e+03
Walter Roberson
Walter Roberson 2022 年 1 月 6 日
True, but the original poster only needed integral powers as they were developing a series approximation to exp()

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File Exchange で Mathematics についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by