PeteyCoco
PeteyCoco

Reputation: 149

How do I solve a function for x in Matlab?

I have this function defined:

% Enter the data that was recorded into two vectors, mass and period
mass = 0 : 200 : 1200;
period = [0.404841 0.444772 0.486921 0.522002 0.558513 0.589238 0.622942];

% Calculate a line of best fit for the data using polyfit()
p = polyfit(mass, period, 1);
fit=@(x) p(1).*x + p(2);

Now I want to solve f(x) = .440086, but can't find a way to do this. I know I could easily work it out by hand, but I want to know how to do this in the future.

Upvotes: 0

Views: 668

Answers (1)

Autonomous
Autonomous

Reputation: 9075

If you want to solve a linear equation such as A*x+B=0, you can easily solve in MATLAB as follows:

p=[0.2 0.5];
constValue=0.440086;
A=p(1);
B=constValue-p(2);
soln=A\B;

If you want to solve a non-linear system of equations, you can use fsolve as follows (Here I am showing how to use it to solve above linear equation):

myFunSO=@(x)0.2*x+0.5-0.440086;  %here you are solving f(x)-0.440086=0
x=fsolve(myFunSO,0.5)  %0.5 is the initial guess.

Both methods should give you the same solution.

Upvotes: 3

Related Questions