How do I plot my own coded function?
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Wilson Zheng
am 27 Jan. 2020
Kommentiert: Walter Roberson
am 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 Kommentare
Akzeptierte Antwort
Walter Roberson
am 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 Kommentare
Walter Roberson
am 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)].');
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Creating, Deleting, and Querying Graphics Objects finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!