Why do i get an error saying "Unrecognized function or variable 'x'."
Show older comments
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
Answers (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 Comments
Rejane Adelie
on 3 Sep 2023
"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
on 3 Sep 2023
Categories
Find more on MATLAB 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!