Using fprintf in a for loop to display the output as a set of coordinate points
10 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Torsten
on 2 May 2025
Edited: Torsten
on 2 May 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])
More Answers (1)
Walter Roberson
on 2 May 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
See Also
Categories
Find more on Numbers and Precision in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!