How do I plot my own coded function?

1 view (last 30 days)
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?

Accepted Answer

Walter Roberson
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
Wilson Zheng
Wilson Zheng on 27 Jan 2020
Edited: Wilson Zheng on 27 Jan 2020
Thank you! Are you sure that this is correct tho? The loop breaks (via the first if statement) at different number of iterations for each input. And the n is printed and returned to show how many loops the function needed.
Walter Roberson
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)].');

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!