2017-05-07 133 views
0

我在确定这个基本逻辑时遇到了问题。给定2个函数:y1和y2,绘制在MATLAB中的x上。你如何确定使用简单for循环和if else语句的交集。这些y1和y2有不止一个交点。我很确定我在循环中丢失了一些东西十字路口MATLAB,多根根

clc 
clear 
x = linspace(0,2); 
y1 = 2.*x + 1; 
y2 = exp(x); 
tol = 0.05; 
x_intercept = zeros(size(x)); 
y_intersect = zeros(size(x)); 
for i = 1:100 
    if abs(y1(i) - y2(i)) == tol 
     y_intersect = y2(x(i)); 
     x_intercept = x(i); 
    end 

end 

plot(x,y1) 
hold on 
plot(x,y2) 
plot(x_intercept, y_intersect,'xr'); 

请问您能否提供帮助?我很抱歉,如果这似乎是一个非常简单的问题,但我已经搜索并找不到答案。我发现的所有东西都是使用polyval/polyfit等,但只显示1个交点。

回答

0

试着改变你的for循环:

ctr=1; 
for i = 1:100 
    if abs(y1(i) - y2(i)) <= tol 
     y_intersect(ctr) = y2(i); 
     x_intercept(ctr) = x(i); 
     ctr=ctr+1; 
    end 

end 
0

您可以使用函数solve找到两条曲线的交点:

clc 
clear 

% Define the symbolic variables 
syms x y 
vars=[x y] 
% Define the two eqautions 
equations=([2*x+1-y == 0,exp(x)-y == 0]) 
% Call SOLVE to find the intersection point 
[sol_x,sol_y]=solve(equations,vars,'Real', true) 
% Get the values of the x and y coordinates of the intersectiin points 
x_inters=double(sol_x) 
y_inters=double(sol_y) 


% Evaluate the two functions (only to plot them) 
x = linspace(0,2); 
y1 = 2.*x + 1; 
y2 = exp(x); 
plot(x,y1) 
hold on 
plot(x,y2) 
% Add the intersection points 
plot(x_inters,y_inters,'or','markerfacecolor','r') 

enter image description here

如果你想/需要使用forif-else报表,您需要先修改if cond银行足球比赛中,你的代码:

if abs(y1(i) - y2(i)) <= tol 

,那么你必须增加,以减少它们之间的距离采样x的数量。

此外,您还必须测试阈值tol的不同值。

该方法将识别若干解决方案,因此您可以在其中识别出y1y2的值之间的差异较小的那些。

一个可能的实现可能是:

clc 
clear 

% x = linspace(0,2); 
% Define the x samaples 
x=0:.001:2 
y1 = 2.*x + 1; 
y2 = exp(x); 
% tol = 0.05; 
tol = 0.001; 
x_intercept = zeros(size(x)); 
% y_intersect = zeros(size(x)); 
y1_intersect = zeros(size(x)); 
y2_intersect = zeros(size(x)); 
% Initialize the counters 
cnt=0; 
once=0; 
% Initialize the minimun_difference 
min_diff=999; 
% for i = 1:100 
% Loop over the xsamples 
for i = 1:length(x) 
    %  if abs(y1(i) - y2(i)) == tol 
    y1_y2_diff=abs(y1(i) - y2(i)); 
    if(y1_y2_diff <= tol) 
     % If the difference is lower than the threshold, set the flag to 
     % increment the number of solutions 
     if(~once) 
     cnt=cnt+1; 
     once=1; 
     end 
     % Store the values for the minimum difference 
     if(y1_y2_diff <= min_diff) 
     min_diff=y1_y2_diff; 
     y1_intersect(cnt) = y1(i); 
     y2_intersect(cnt) = y2(i); 
     x_intercept(cnt) = x(i); 
     end 
    else 
     % Rese the flag 
     min_diff=999; 
     once=0; 
    end 
end 

plot(x,y1) 
hold on 
plot(x,y2) 
% plot(x_intercept, y_intersect,'xr'); 
plot(x_intercept(1:cnt), y1_intersect(1:cnt),'xr'); 
plot(x_intercept(1:cnt), y2_intersect(1:cnt),'dr'); 

希望这有助于

Qapla”

+0

非常感谢你。 – mle0312

+0

不客气。如果答案解决了您的问题,您可以接受它让社区知道问题已经结束 –