Using fprintf in a for loop to display the output as a set of coordinate points
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
rezheen
el 2 de Mayo de 2025
Comentada: rezheen
el 2 de Mayo de 2025
Hi, I'm having trouble displaying the output of a math problem about critical points of a function as a set of coordinate points. This is my code
syms x y real
y=x*(4-x)^3;dy=diff(y); x_roots=solve(dy,x); y_x_roots=subs(y,x_roots);
for j=1
disp('The critical point(s) is/are')
for k =length(x_roots) & x_roots~=0
fprintf("(%d,%d)\n",x_roots, y_x_roots)
end
end
Prints as output:
The critical point(s) is/are
(1,4)
(4,27)
(0,0)
But it should be:
The critical point(s) is/are
(1,27)
(4,0)
(4,0)
Also, the x=4 is multiplicity of 2 or greater. Is there a way I can display it only once?
Thank you.
0 comentarios
Respuesta aceptada
Torsten
el 2 de Mayo de 2025
Editada: Torsten
el 2 de Mayo de 2025
syms x y real
y=x*(4-x)^3;dy=diff(y); x_roots=solve(dy,x); y_x_roots=subs(y,x_roots);
for j=1
disp('The critical point(s) is/are')
[~,idx] = unique(x_roots);
x_roots = x_roots(idx);
y_x_roots = y_x_roots(idx);
for k = 1:length(x_roots)
if x_roots(k)~=0
fprintf("(%d,%d)\n",x_roots(k), y_x_roots(k))
end
end
end
fplot(y,[0 5])
Más respuestas (1)
Walter Roberson
el 2 de Mayo de 2025
The basic problem is that fprintf() consumes all of each argument before going on to the next argument. Combine that with the fact that you were attempting to print all of the vector at the same time because you did not form the for loop properly.
syms x y real
y=x*(4-x)^3;dy=diff(y); x_roots=solve(dy,x); y_x_roots=subs(y,x_roots);
disp('The critical point(s) is/are')
for k = 1:length(x_roots)
if x_roots(k)~=0
fprintf("(%d,%d)\n",x_roots(k), y_x_roots(k));
end
end
Ver también
Categorías
Más información sobre Numbers and Precision en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!