How do I plot my own coded function?
7 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Walter Roberson
2020-1-27
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 个评论
Walter Roberson
2020-1-27
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)].');
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating, Deleting, and Querying Graphics Objects 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!