Reputation: 31
Lets say, I have a function 'x' and a function '2sin(x)'
How do I output the intersects, i.e. the roots in MATLAB? I can easily plot the two functions and find them that way but surely there must exist an absolute way of doing this.
Upvotes: 3
Views: 12514
Reputation: 36710
When writing the comments, I thought that
syms x; solve(x==2*sin(x))
would return the expected result. At least in Matlab 2013b solve
fails to find a analytic solution for this problem, falling back to a numeric solver only returning one solution, 0
.
An alternative is
s = feval(symengine,'numeric::solve',2*sin(x)==x,x,'AllRealRoots')
which is taken from this answer to a similar question. Besides using AllRealRoots
you could use a numeric solver, manually setting starting points which roughly match the values you have read from the graph. This wa you get precise results:
[fzero(@(x)f(x)-g(x),-2),fzero(@(x)f(x)-g(x),0),fzero(@(x)f(x)-g(x),2)]
For a higher precision you could switch from fzero
to vpasolve
, but fzero
is probably sufficient and faster.
Upvotes: 3
Reputation: 35080
If you have two analytical (by which I mean symbolic) functions, you can define their difference and use fzero
to find a zero, i.e. the root:
f = @(x) x; %defines a function f(x)
g = @(x) 2*sin(x); %defines a function g(x)
%solve f==g
xroot = fzero(@(x)f(x)-g(x),0.5); %starts search from x==0.5
For tricky functions you might have to set a good starting point, and it will only find one solution even if there are multiple ones.
The constructs seen above @(x) something-with-x
are called anonymous functions, and they can be extended to multivariate cases as well, like @(x,y) 3*x.*y+c
assuming that c
is a variable that has been assigned a value earlier.
Upvotes: 3