How do I plot my own coded function?
11 ビュー (過去 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!