MATLAB: How to solve equation with for loop? If it’s not possible to, is there any alternative options

for loopfsolveMATLABsolvesum

Hi, I'm trying to solve a single-variable equation using Matlab. The equation is:
where C is the variable I want to solve.
My code is:
%Read Data
r=1;
n=6;
beta=-0.8;
alpha_1=0.2;
alpha_2=0.8;
V=[4.13 1.15 .57 .36 .34 .21];
B=2;
%Initialization
D=[1:n];
A=[1:n];
I=ones(1,n);
%Iteration
%%Solve C
fun = @solveC;
C0 = 0.1;
C = fsolve(@solveC,C0);
And the solveC function is defined as:
function B = solveC(C)
B = 0;
for j = 1:n
B=B+I(j).*((-(alpha_1+alpha_2)+sqrt((alpha_1+alpha_2).^2-4.*beta.*(log(C)-log(r)-log(r./length(A))-log(V(j)))))./(beta));
end
The error code is:
Error: File: solveC.m Line: 18 Column: 4
Function definitions are not permitted in this context.
Error in fsolve (line 230)
fuser = feval(funfcn{3},x,varargin{:});
Error in RA_Algorithm (line 23)
C = fsolve(@solveC,C0);
Caused by:
Failure in initial objective function evaluation. FSOLVE cannot continue.
Can anyone help me with this??? I'm pretty new to Matlab, please help me to solve this equation… Thanks a lot!

Best Answer

Meilin
you may want to solve for complex variable. Before solving, why not having a look how the function looks like:
format long
beta=-0.8;
alpha_1=0.2;
alpha_2=0.8;
B=2;
V=[4.13 1.15 .57 .36 .34 .21];
you do neither define q or b
q_i_b=1+1j;
b=1;
N=10;
Dre_range=[-N:.1:N];
Dim_range=[-N:.1:N];
[Dre,Dim]=meshgrid(Dre_range,Dim_range);
D=Dre+(0+1j)*Dim;
% the formula only has conj(D)
xre=1;xim=1;
sweep for all values of V needed
V1=V(1);
in the formula you use
B=B+I(j).*((-(alpha_1+alpha_2)+sqrt((alpha_1+alpha_2).^2-4.*beta.*(log(C)-log(r)-log(r./length(A))-log(V(j)))))./(beta));
why do you put B on both sides of the equal?
L1=-1/beta*(abs(conj(D))*(alpha_1+alpha_2));
L2=((alpha_1+alpha_2)^2-4*beta*(log(conj(xre+j*xim)) -log(conj(q_i_b))-log(V1))).^.5;
L3=L1+L2;
Z=sum(sum(L3))-B;
Zre=real(Z);Zim=imag(Z);
surf(Zre,Zim);
and the function, in complex plane, looks like
that from a side looks like
so you are looking for elliptic/circle type solutions, depending upon V, q, b, that you have to sweep, with loops.
Do you want me to solve? or are you confident you can solve it now, so that you can say you solve it, not some one else?
Meilin would you please be so kind to mark my answer as Accepted Answer?
To any other reader, please if you find this answer of any help solving your question,
please click on the thumbs-up vote link,
thanks in advance
John
Related Question