필터 지우기
필터 지우기

I am getting "Array indices must be positive integers or logical values" in my code.

조회 수: 1 (최근 30일)
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?

채택된 답변

Voss
Voss 2023년 12월 4일
You have created a variable called "factorial", the existence of which prevents you from using the "factorial" function.
Run
clear factorial
and then run your script again.
  댓글 수: 4
Voss
Voss 2023년 12월 4일
@madhan ravi: Thanks!
@Arda: You're welcome!
Probably you created the variable "factorial" in another script (or an older version of this script). Scripts run in the base workspace and operate on variables in the base workspace. All scripts you run share the same workspace (the base workspace). Once a variable is in the base workspace, it stays there until it is cleared (or until MATLAB is restarted).
Functions, on the other hand, each have their own workspace which is created when the function starts running and is cleared when the function exits. That is, (by default) no variables in a function's workspace persist to potentially interfere with the running of another function. So this problem would not have happened if the code had been in a function instead of a script.
Arda
Arda 2023년 12월 4일
Yeah you're right, I was doing another code about factorials and I forgot to clear the previous variable defined to factorial. I don't how missed it but it happens right? Anyways, have a great day!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Shoresh Shokoohi
Shoresh Shokoohi 2023년 12월 4일
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
Dyuman Joshi
Dyuman Joshi 2023년 12월 5일
"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?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by