Question

I would like to know how can I get both the positive and the negative solution from a sqrt in Matlab.

For example if I have:

sin(a) = sqrt(1-cos(a)^2); 
Was it helpful?

Solution 2

MATLAB (and every other programming language that I know of) only returns the principal square root of x when calling sqrt(x) or equivalent.

How you'd write the square root of x mathematically, is

s = ±√x

which is just a shorthand for writing the whole solution set

s = {+√x -√x}

In MATLAB, you'd write it the same as this last case, but with slightly different syntax,

s = [+sqrt(x) -sqrt(x)]

which can be computed more efficiently if you "factor out" the sqrt:

s = sqrt(x) * [1 -1]

So, for your case,

s = sqrt(1-cos(a)^2) * [1 -1]

or, if you so desire,

s = sin(acos(a)) * [1 -1]

which is a tad slower, but perhaps more readable (and actually a bit more accurate as well).

Now of course, if you can somehow find the components whose quotient results in the value of your cosine, then you wouldn't have to deal with all this messy business of course....

OTHER TIPS

The docs don't say anything specific about always only providing the positive square root but it does seem like a fair assumption in which case you can get the negative square pretty easily like this:

p = sqrt(1-cos(a)^2);
n = -sqrt(1-cos(a)^2);

btw assigning to sin(a) like that is going to create a variable called sin which will hide the sin function leading to many possible errors, so I would highly recommend choosing a different variable name.

sqrt does not solve equations, only gives numerical output. You will need to formulate your equation as you need it, and then you can use sqrt(...) -1*sqrt(...) to give your positive and negative outputs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top