finding x and y intercept
조회 수: 111 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
채택된 답변
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!