How do I plot my own coded function?
1 view (last 30 days)
Show older comments
Wilson Zheng
on 27 Jan 2020
Commented: Walter Roberson
on 27 Jan 2020
Hi all, my code creates a function that finds the natural log of the input.
function [answer, n] = mylog(x)
fprintf("calculating the log:\n");
tolerance = 1e-10;
maxIterations = 300;
answer = 0;
for n=0:maxIterations
answer = answer + (2/(2*n+1)) * ((x-1)/(x+1))^(2*n+1);
error = (2/(2*n+3)) * ((x-1)/(x+1))^(2*n+3);
relError = abs(error);
if (relError < tolerance)
break;
end
end
if (relError > tolerance)
fprintf("The log(x) could not be found\n");
else
fprintf("mylog(x) = %4e and n(x) = %i\n", answer, n);
end
To the best of my knowledge, the code works perfectly fine but I don't understand how to plot the graph (x, mylog(x)). I use x=linspace(0.001, 1), and I see that for a native function you can just do y=sin(x) and then its easily plotted. But when I try to do y=mylog(x), y is just a single value and not an array. What am I doing wrong and how do I fix it?
0 Comments
Accepted Answer
Walter Roberson
on 27 Jan 2020
function [answer, n] = mylog(x)
fprintf("calculating the log:\n");
tolerance = 1e-10;
maxIterations = 300;
answer = 0;
for n=0:maxIterations
answer = answer + (2/(2*n+1)) * ((x-1)./(x+1)).^(2*n+1);
error = (2/(2*n+3)) * ((x-1)./(x+1)).^(2*n+3);
relError = abs(error);
if all(relError < tolerance)
break;
end
end
if any(relError > tolerance)
fprintf("The log(x) could not be found\n");
else
fprintf("mylog(x) = %4e and n(x) = %i\n", [answer(:), n(:)].');
end
2 Comments
Walter Roberson
on 27 Jan 2020
The function is nearly correct, and in particular is correct with regards to the point you are discussing.
The number of iterations used would be the worst-case over all of the x: it will not stop until you are out of iterations or all of the logs are found to the required accuracy. This is reasonable behaviour for a function whose operation on vectors has not been otherwise defined.
The error in the function is that the line
fprintf("mylog(x) = %4e and n(x) = %i\n", [answer(:), n(:)].');
should be
fprintf("mylog(x) = %4e and n(x) = %i\n", [answer(:), repmat(n,length(answer),1)].');
More Answers (0)
See Also
Categories
Find more on Axis Labels 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!