Using fprintf in a for loop to display the output as a set of coordinate points
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Torsten
le 2 Mai 2025
Modifié(e) : Torsten
le 2 Mai 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])
Plus de réponses (1)
Walter Roberson
le 2 Mai 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
Voir également
Catégories
En savoir plus sur Numbers and Precision dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!