Using fprintf in a for loop to display the output as a set of coordinate points

2 次查看(过去 30 天)
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.

采纳的回答

Torsten
Torsten 2025-5-2
编辑:Torsten 2025-5-2
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
The critical point(s) is/are
(1,27) (4,0)
fplot(y,[0 5])

更多回答(1 个)

Walter Roberson
Walter Roberson 2025-5-2
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')
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
(1,27) (4,0) (4,0)

类别

Help CenterFile Exchange 中查找有关 Numbers and Precision 的更多信息

产品


版本

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by