Why do i get an error saying "Unrecognized function or variable 'x'."
이전 댓글 표시
I am trying to solve a function with header [approx, true err, rel true err] = myDouble Exp(x, N), to compute for approximation of e^x² using the first N terms of the Taylor series expansion, also computing for true error and relative true error. The function myDoubleExp must take array inputs.
function [approx, true_err, rel_true_err] = MyDoubleExp(x,N)
approx = zeros(size(x));
true_err = zeros(size(x));
rel_true_err = zeros(size(x));
for n = 0:N
term = (x.^(2*n)) / factorial(n);
approx = approx + term;
end
true_value = exp(x.^2);
true_err = true_value - approx;
for i = 1:numel(x)
if true_value(i) == 0
rel_true_err(i) = 0;
else
rel_true_err(i) = abs(true_err(i)) / abs(true_value(i))*100;
end
end
end
If I run the above code I receive the following error
>> MyDoubleExp(x, N)
Unrecognized function or variable 'x'.
What correction should be done in order to get the code running? I am using MATLAB version R2023a
답변 (1개)
You have not defined ‘x’ specifically in your calling script prior to calling the function.
Try something like this —
x = pi;
N = 5;
[approx, true_err, rel_true_err] = MyDoubleExp(x,N)
function [approx, true_err, rel_true_err] = MyDoubleExp(x,N)
approx = zeros(size(x));
true_err = zeros(size(x));
rel_true_err = zeros(size(x));
for n = 0:N
term = (x.^(2*n)) / factorial(n);
approx = approx + term;
end
true_value = exp(x.^2);
true_err = true_value - approx;
for i = 1:numel(x)
if true_value(i) == 0
rel_true_err(i) = 0;
else
rel_true_err(i) = abs(true_err(i)) / abs(true_value(i))*100;
end
end
end
It is almost always best to write and run scripts rather than executing code in the Command Window.
.
댓글 수: 3
Rejane Adelie
2023년 9월 3일
"It was not given in the problem so i didn't defined 'x', is it possible without it?"
You need to provide a value to run the code, it does not matter if you call the variable x, y, z or xyz or any other valid variable name.
You can also directly call the function -
%I have not defined x and N, but directly used the values
% vv v
[approx, true_err, rel_true_err] = MyDoubleExp(pi,5)
function [approx, true_err, rel_true_err] = MyDoubleExp(x,N)
approx = zeros(size(x));
true_err = zeros(size(x));
rel_true_err = zeros(size(x));
for n = 0:N
term = (x.^(2*n)) / factorial(n);
approx = approx + term;
end
true_value = exp(x.^2);
true_err = true_value - approx;
for i = 1:numel(x)
if true_value(i) == 0
rel_true_err(i) = 0;
else
rel_true_err(i) = abs(true_err(i)) / abs(true_value(i))*100;
end
end
end
Star Strider
2023년 9월 3일
카테고리
도움말 센터 및 File Exchange에서 C Matrix API에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!