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)
approx = 1.3956e+03
true_err = 1.7938e+04
rel_true_err = 92.7817
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 个评论

It was not given in the problem so i didn't defined 'x', is it possible without it?
"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)
approx = 1.3956e+03
true_err = 1.7938e+04
rel_true_err = 92.7817
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

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by