How can i solve function with an dependent variable?

There is a g(u) function and u variable's values are dependent to g(u) function, its derivative and smaller u.
I do not know how to write this as a matlab code.

 Accepted Answer

Below I show the structure of a possible solution. The rest is up to you. Feel free to comment if you have a specific question.
g=@(mu,B1,B2,B3,a1,a2,a3) B1./a1;
g_=@(mu,B1,B2,B3,a1,a2,a3) 2./(a1-mu);
mu_k=0;
while true
mu_kp1=mu_k-g(mu_k,B1,B2,B3,a1,a2,a3)./g_(mu_k,B1,B2,B3,a1,a2,a3);
if mu_kp1/mu_k < 1
break
end
end

6 Comments

i tried but it was not working. how can i write u as matrix? so i thought i could create a for loop by giving k value.
You can encode mu as a vector if you want. Is that interesting?
And what did you try? The code I showed isn't finished, I left the specifics for you. Please show you put in some effort.
Below is the edit required to make mu a vector.
g=@(mu,B1,B2,B3,a1,a2,a3) B1./a1;
g_=@(mu,B1,B2,B3,a1,a2,a3) 2./(a1-mu);
mu=0;k=1;
while true
mu(k+1)=mu(k)-g(mu(k),B1,B2,B3,a1,a2,a3)./g_(mu(k),B1,B2,B3,a1,a2,a3);
if mu_(k+1)/mu(k) < 1
break
end
end
g = @(u) (B1./(al1 - u)).^2 + (B2./(al2 - u)).^2 + (B3./(al3 - u)).^2 -1;
derivg = @(u) 2/(al1-u).*(B1./(al1 - u)).^2 + 2/(al2-u).*(B2./(al2 - u)).^2 + 2/(al3-u).*(B3./(al3 - u)).^2 ;
u=0; k=1;
while true
u(k+1)= u(k)-g(u(k))./derivg(u(k));
if abs(u(k)- u(k-1)./u(k)) < 0.000001
break
end
end
i did this but i got this error "Unable to perform assignment because the left and right sides have a different number of elements." at
u(k+1)= u(k)-g(u(k))./derivg(u(k));
line.
and said that i should consider preallocating "u". (btw other variables are constant.)
I do not know how to preallocate it.
u = zeros(1, 1000000);
i preallocated like this. However i still have the error "Unable to perform assignment because the left and right sides have a different number of elements.".
After a minor edit, the code runs fine. And you only need pre-allocation if you expect many iterations, in which case I would suggest avoiding storing all intermediate values, unless the explicit goal is to find the trend in iterations of mu for different values of your betas and alphas.
%generate random values, but make sure they are the same every run
rng(0);[B1,al1,B2,al2,B3,al3]=deal(rand);
g = @(u) (B1./(al1 - u)).^2 + (B2./(al2 - u)).^2 + (B3./(al3 - u)).^2 -1;
derivg = @(u) 2/(al1-u).*(B1./(al1 - u)).^2 + 2/(al2-u).*(B2./(al2 - u)).^2 + 2/(al3-u).*(B3./(al3 - u)).^2 ;
u=0; k=1;
while true
u(k+1)= u(k)-g(u(k))./derivg(u(k));
k=k+1;
if abs((u(k)- u(k-1))./u(k)) < 0.000001
% ^ ^
% you forgot these
break
end
end
disp(u)
0 -0.2716 -0.4929 -0.5853 -0.5963 -0.5964 -0.5964
thank you so much for helping me

Sign in to comment.

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!