Solve MATLAB fsolve Equation: x-(r/4)*sin(pi*x)=0

  • Thread starter Thread starter krnhseya
  • Start date Start date
  • Tags Tags
    Matlab
AI Thread Summary
The discussion focuses on solving the equation x - (r/4)*sin(pi*x) = 0 using MATLAB's fsolve function, with r varying from 0 to 4. The user encounters issues because fsolve requires a function with multiple equations, while their problem only presents one equation. Suggestions include defining r as a constant outside the loop and creating a separate function that incorporates r for each iteration. Additionally, it is advised to structure the function to ensure compatibility with fsolve's requirements for multivariable functions. The overall goal is to generate a plot of r versus the solution variable x.
krnhseya
Messages
102
Reaction score
0
I think I posted in a wrong forum...I wasn't sure which category I was supposed to post this under but here it goes...

1. Homework Statement

Find x where r varies from 0 to 4.

2. Homework Equations

x-(r/4)*sin(pi*x)=0

3. The Attempt at a Solution

The problem that I ran into with MATLAB is that when I create a sub-m file for fsolve, it requires 2 equations whereas I only have 1 equation.

function F=myfun(x,r)
F(1)=x-(r/4)*sin(pi*x);

My executable is:

var_new=[];
for r=0:0.01:4;
var=fsolve(@myfun,0.5)
var_new=[var_new var]
i=i+1;
end

I expect to get "var" variable to be a single number where my "relevant equation" is set to zero. var_new is simply creating an array for me to plot r versus var.

Thank you.
 
Physics news on Phys.org
So 1 equation and 1 variable...Looks darn easy but I just can't figure this out and MATLAB examples that I can find (including built-in help) doesn't get me any more help...Anyone...?
 
My new attempt...

i=1;
new_x=[];
newnewx=[];

for r=0.5:0.01:4;
new_x(i)=fsolve(@myfun,[0 r]);
newnewx(i)=((r*pi)/4)*cos(pi*new_x(i));
i=i+1;
end
r=0.5:0.01:4;

plot(r,newnewx)

where the myfun is:

function F=myfun(x)
x=x(1);
r=x(2);
F(1)=x-((r/4)*sin(pi*x));
 
What you can do is define r outside of the loop, then loop through a variable i that goes from 1:length(r). Inside of the loop define the function F so that r is not a variable but a constant for each iteration.

But if you need to have the function in a separate script you can try and create a new function F2(x) = F(x,r) where r is some specific number. I don't think fsolve will just accept a multivariable function.
 

Similar threads

Back
Top