I am getting "Array indices must be positive integers or logical values" in my code.
Show older comments
x = 5;
errorThreshold = 0.001;
approximatedCos = 0;
for i = 0:20
term = ((-1)^i) * (x^(2*i)) / factorial(2*i);
approximatedCos = approximatedCos + term;
if abs(term) < errorThreshold
break;
end
end
fprintf('Approximated cos(%g):%g\n', x, approximatedCos);
I am getting the error in the term = ((-1)^i) * (x^(2*i)) / factorial(2*i); section and I couldn't fix it. Can someone help?
Accepted Answer
More Answers (1)
Shoresh Shokoohi
on 4 Dec 2023
0 votes
You need to define it yourself or use the factorial function from the MATLAB Statistics and Machine Learning Toolbox.
Here is an example of how you can define the factorial function in your code:
x = 5;
errorThreshold = 0.001;
approximatedCos = 0;
% Define factorial function
fact = @(n) prod(1:n);
for i = 0:20
term = ((-1)^i) * (x^(2*i)) / fact(2*i);
approximatedCos = approximatedCos + term;
if abs(term) < errorThreshold
break;
end
end
fprintf('Approximated cos(%g): %g\n', x, approximatedCos);
1 Comment
Dyuman Joshi
on 5 Dec 2023
"You need to define it yourself or use the factorial function from the MATLAB Statistics and Machine Learning Toolbox."
Why do that when there is a built-in function available?
Categories
Find more on Encryption / Cryptography 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!