MATLAB: System of non linear equations of the same form

fsolvenonlinearnonlinear equation

Hi everybody
I'm new to matlab so i could have done stupid errors.
I have to solve a nxn system of non linear equations of the same form A+B-C==0, where n is the DOF number of a multibody system (so there are n genralized coordinates th_1,…,th_n) and the (n+1)th unkonown is a load P. So i have n equations and n+1 unknown. What i want to do is to to assign a value to the first coordinate th_1 (=alpha) and solve the system (what i really care about is P(th(1)), i don't care about the other coordinates). I want to control n because the idea is that the bigger n, the better approximation. As i said the equation are all of the same form i want to define the equation with a for cycle with i=1:n. I tried several solutions but none of them worked. I defined the system of equation in a function. Note that the vector th collects the coordinates from 2 to n (so th(1) is actually th_2)
function F = myfun(P,th)
global n E Jx l alpha
k = E*Jx*n/l/P;
A = 0;
B = l/(2*n*(alpha-th(1)))*(cos(th(1))-cos(alpha));
C = (alpha-th(1))*k;
F(1) = A+B-C;
for i = 2:n-1
A = A+l/n/(th(i-1)-th(i))*(cos(th(i))-cos(th(i-1)));
%B = l/n/(th(i)-th(i+1))*((sin(th(i))-sin(th(i+1)))/(th(i)-th(i+1))-cos(th(i)));
B = l/(2*n*(th(i-1)-th(i)))*(cos(th(i))-cos(th(i-1)));
C = (th(i-1)-th(i))*k;
F(i) = A+B-C;
end
%B = l/n/th(n)*(sin(th(n))/th(n)-cos(th(n)));
B = l/(2*n*th(n-1))*(1-cos(th(n-1)));
C = th(n-1)*k;
F(n) = A+B-C;
end
I then tried to solve with fsolve but i don't know how to formalize the problem. here's one of my attempt
E = 1; Jx = 1; l = 1; Pcr = pi^2*E*Jx/(2*l)^2;
n = input('n = ');
alpha = pi/8;
x0 = [Pcr alpha*ones(1,n-1)];
fsolve(@myfun,x0)
i get
Error using /
Matrix dimensions must agree.
Error in myfun (line 5)
k = E*Jx*n/l/P;
Error in fsolve (line 230)
fuser = feval(funfcn{3},x,varargin{:});
Error in untitled (line 8)
fsolve(@myfun,x0)
Caused by:
Failure in initial objective function evaluation. FSOLVE cannot continue.
thanks for your help

Best Answer

x = fsolve(@(x)myfun(x(1),x(2:n),x0)