Using fprintf in a for loop to display the output as a set of coordinate points
1 回表示 (過去 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.
0 件のコメント
採用された回答
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
fplot(y,[0 5])
その他の回答 (1 件)
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')
for k = 1:length(x_roots)
if x_roots(k)~=0
fprintf("(%d,%d)\n",x_roots(k), y_x_roots(k));
end
end
参考
カテゴリ
Help Center および File Exchange で Numbers and Precision についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!