1

I have the equation:

sin(x) = exp(a)+4

x = 1:.1:20

a = 0.02

I know i can use roots or fzero functions inside a loop to determine the roots.

How to use one or both of the above functions to find all the roots and them count them all in sin(x) = exp(a)-4

I wrote this code, it finds the zeros with fzero and marks them in plot. But how to modify to sin(x) = exp(a)-4 so finds all roots and then counts the number of finded roots and output the results.

x = 0:.1:20;
f = @(x) sin(x) + 4;
c = zeros(length(x),1);
for i=0:length(x)
    c = fzero(f,i);
    axis([0, 20, -2, 1])
    plot(x, f(x));
    title('Zeros de f(x) = sin(x) + 4');
    hold on
    plot(c, f(c),'-xr')
    hold on
end

EDIT

I used fzero inside a loop with the unique function to output, but it never outputs just the unique values. I outputs all duplicates. Anyone know why?

My new code:

h = @(x) cos(x);
g = @(x) exp(a*x)-1;

        f = @(x) h(x) - g(x);
        v = zeros(length(x),1);
        for i=0:length(x)
            v = fzero(f,i);
            [s] = unique(v)
        end
André Castro
  • 1,527
  • 6
  • 33
  • 60

1 Answers1

1

In short, you can rearrange any equation problem to a root-finding problem by subtraction:

f = @(x) (sin(x) - (exp(a) + 4));

roots would operate on polynomials only. fzero is an iterative algorithm that may converge to one root close to the initial guess i. Afterwards, you can use the unique function to extract the distinct solutions.

SpamBot
  • 1,438
  • 11
  • 28
  • Many thanks... Please see my EDIT, as the duplicate function is not working as it should. – André Castro Nov 19 '15 at 10:24
  • 1. Make sure that you stack all results of fzero in a vector. 2. Outside that loop, you really want to use a unique function that uses a tolerance, similar to answer http://stackoverflow.com/a/1993859/2079934 Reason is that fzero is only an approximation and results differ at the order of the float precision, so you want to set that as a tolerance, for instance 10^-12 – SpamBot Dec 18 '15 at 09:57