Alternative for a for loop. How would I write this code without using a for loop?

function approx = approxCosineFunction(x, t)
approx=1;
for i=1:1:t-1
addterm = (-1)^i*(x^(2*i))/factorial(2*i);
approx = approx + addterm;
end
end

2 件のコメント

Matt J
Matt J 2017 年 11 月 2 日
There are already no for loops in the code that you've shown.
John Barber
John Barber 2017 年 11 月 2 日
oops. Fixed it

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

 採用された回答

James Tursa
James Tursa 2017 年 11 月 2 日
編集済み: James Tursa 2017 年 11 月 2 日
To get the correct result, you need to make that divide an element-wise divide, and then add up the resulting terms into approx. E.g.,
addterm = (-1).^(1:1:t-1).*(x.^(2.*(1:1:t-1)))./factorial(2.*(1:1:t-1)); % <-- changed / to ./
approx = approx + sum(addterm); % <-- added the sum( )
But this will just give you the last approximation. If you wanted to return a vector containing all of the intermediate results as well, you could use cumsum instead. E.g.,
approx = approx + cumsum(addterm);

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

質問済み:

2017 年 11 月 2 日

編集済み:

2017 年 11 月 2 日

Community Treasure Hunt

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

Start Hunting!

Translated by