How to solve equation with for loop? If it's not possible to, is there any alternative options?
Show older comments
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!
Accepted Answer
More Answers (2)
Walter Roberson
on 8 Aug 2016
You need to take the code starting from
function B = solveC(C)
and store it into a file solveC.m
Meilin He
on 8 Aug 2016
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
