finding x and y intercept

45 ビュー (過去 30 日間)
Reynand Joe
Reynand Joe 2023 年 4 月 22 日
編集済み: Rik 2023 年 4 月 24 日
Hi i want to ask something. How do I find the x and y intercepts of a function using gui
here is my code
funcString = get(handles.edit1,'String');
funcHandle = str2func(['@(x)' funcString]);
x = linspace(100,-100,200);
y = funcHandle(x);
plot(handles.axes1,x,y);
the function is user defined

採用された回答

LeoAiE
LeoAiE 2023 年 4 月 23 日
I think you can first calculate the x-intercepts by checking for sign changes in the y values, then using fzero to find the exact root. We store the x-intercepts in the x_intercepts variable. Next, we evaluate the function at x = 0 to find the y-intercept and store it in the y_intercept variable.
Finally, we display the x and y-intercepts in the GUI by setting the 'String' property of text elements handles.x_intercepts_text and handles.y_intercept_text, respectively. We also add markers for the intercepts on the plot.
Please note that you'll need to add the text elements x_intercepts_text and y_intercept_text to your GUI for displaying the intercepts. You can do this using MATLAB's GUIDE or App Designer.
% Your existing code
funcString = get(handles.edit1,'String');
funcHandle = str2func(['@(x)' funcString]);
x = linspace(-100, 100, 200);
y = funcHandle(x);
plot(handles.axes1, x, y);
% Find x-intercept(s)
x_intercepts = [];
tol = 1e-6; % Tolerance for identifying unique roots
for i = 1:length(x) - 1
if y(i) * y(i + 1) <= 0
root = fzero(funcHandle, [x(i), x(i + 1)]);
if isempty(x_intercepts) || min(abs(x_intercepts - root)) > tol
x_intercepts = [x_intercepts, root];
end
end
end
% Find y-intercept
y_intercept = funcHandle(0);
% Display the results
set(handles.x_intercepts_text, 'String', sprintf('X-Intercepts: %s', mat2str(x_intercepts, 4)));
set(handles.y_intercept_text, 'String', sprintf('Y-Intercept: %.4f', y_intercept));
% Add intercepts to the plot
hold(handles.axes1, 'on');
plot(handles.axes1, x_intercepts, zeros(size(x_intercepts)), 'ro');
plot(handles.axes1, 0, y_intercept, 'bo');
hold(handles.axes1, 'off');
  2 件のコメント
Reynand Joe
Reynand Joe 2023 年 4 月 23 日
thanks a lot!
LeoAiE
LeoAiE 2023 年 4 月 23 日
Please accept the answer if you like it! Thanks

サインインしてコメントする。

その他の回答 (0 件)

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by