0

I am plotting two equations against each other, I did this by creating a 2x100 array and a linspace. I have successfully plotted the curves, but I don't know how to find the values (of u and c) that they intersect at?

I have tried intersect(,), find(==), but they doesn't work with my problem, I think because it uses an if loop.

Here is my code:

clear all
A = 3;
B = 1.8;
d = 1;
c2 = 1;
c1 = 0.7;
s = 0.1;

c = linspace(0,1.5);
u = zeros(2,numel(c));

for i = 1:numel(c)
u(1,i)= c(i) / ((A/(c(i)+1))-(d*c(i)/(c(i)+c2))) ; 
u(2,i)= B*c(i) /(c(i)+c1)-s;
end

hold on
plot(c,u(1,:),'r');
plot(c,u(2,:),'g');
hold off

graph

Steve
  • 1,579
  • 10
  • 23
  • 1
    First thing: you don't need a loop here: `u(1,:)= c ./ ((A./(c+1))-(d*c./(c+c2))) ; u(2,:)= B*c ./(c+c1)-s;` – obchardon Nov 02 '16 at 13:11

2 Answers2

2

Since you are evaluating at discrete points, you have not hit a point where u_1==u_2. You can see the point where they are closest with

>> [diff_min, diff_min_index] = min(abs(u(1,:)-u(2,:)))

diff_min =

    0.0046


diff_min_index =

    65
>> hold on
>> plot(c(diff_min_index),u(1,diff_min_index))
>> hold off

Perhaps more helpfully, you can find the indices when u_1-u_2 changes sign:

>> find(diff(sign(u(1,:)-u(2,:)))~=0)

ans =

     4    65

To find the intersection, you could define a function as the difference of your two functions f=u_1 - u_2 and search for roots using the MATLAB function fzero: You could do this by defining your original functions as anonymous functions:

>> f1 = @(c) c./((A./(c+1)) - d*c./(c+c2)); 
>> f2 = @(c) B*c./(c+c1) - s;
>> f_diff = @(c) f1(c) - f2(c);
>> fzero(f_diff,0)

ans =

    0.0488

>> fzero(f_diff,1)

ans =

    0.9729

If the original functions are not available, one could use griddedInterpolant.

Steve
  • 1,579
  • 10
  • 23
  • Thank you so much!! I used your last suggestion of making them into functions. Very kind, thank you for your time. – Stefani Notti Nov 04 '16 at 14:21
  • @StefaniNotti No problem, glad we could help. Please consider marking an answer as accepted. You can read more on the page [Help Center > Answering](http://stackoverflow.com/help/accepted-answer). – Steve Nov 04 '16 at 17:51
1

The low-cost version:

With this method I'm just looking at the nearest point before/after the intersection:

ind = find(diff([u(1,:)-u(2,:)]>0))
interx = c(ind);

The best option (IMO) is to use this method to approximate the intersection points and then use the @Steve's solution to determine a more precise solution.

for i = 1:length(interx)
fzero(f_diff,interx(i))
end
obchardon
  • 10,614
  • 1
  • 17
  • 33
  • I like the loop and the *best* starting guess. You don't need the `~=0` in the find, since you have `>0`. (I guess also true in my use of `find` actually) – Steve Nov 02 '16 at 14:01