MATLAB Answers

## Conditional values and equations

Asked by Giuseppe Pintori

### Giuseppe Pintori (view profile)

on 12 Oct 2019
Latest activity Commented on by Giuseppe Pintori

### Giuseppe Pintori (view profile)

on 14 Oct 2019
Accepted Answer by Thiago Henrique Gomes Lobato

### Thiago Henrique Gomes Lobato (view profile)

Hi guys, I need to ask you some tips.
Let's say we have a situation like the following:
alpha = [];
gm = [];
gs = [];
s_1 = 0.3;
s_T = 0.7;
I need to find the values of alpha, gm and gs such that the initial and final values of s (a vector) are the ones I've writed.
And what if alpha, gm and gs are called inside an equation? Like:
b(t) = (gs+h(t-1))*b(t-1);
a(t) = (gm+v(t-1))*a(t-1);
s = (alpha*a.^z+(1-alpha)*b.^z).^(1/z-1).*alpha.*a.^(z-1);
I don't know if I explained myself well.

darova

### darova (view profile)

on 12 Oct 2019
DId you try for loop?

Sign in to comment.

## 1 Answer

### Thiago Henrique Gomes Lobato (view profile)

Answer by Thiago Henrique Gomes Lobato

### Thiago Henrique Gomes Lobato (view profile)

on 13 Oct 2019
Accepted Answer

What you want to do is a non-linear optimization of the three parameters alpha, gm and gs. For you to do this you have to define a optimization function which would have as error the difference between the values that you want and the ones that you get and then minimize it. You didn't give neither your full function nor all variables, but I tried to define an example function as closest as I could from what you wrote to illustrate the process:
x0 = [1,1,1]; % initial Guess
[x,fval] = fminsearch(@(x)opt(x,0),x0) % Do the optimization
S = opt(x,1); % Get and show the initial and last entries from S
S_first_and_final = [S(1),S(end)]
function Error = opt(x,getSValues)
% Those variables are your optimization vector
alpha = x(1);
gm = x(2);
gs = x(3);
% Here I just randomly define a function that may look like the one you have
Steps = 10;
b = zeros(Steps,1);
a = zeros(Steps,1);
b(1) = 2;
a(1) = 1;
h = ones(Steps,1);
v = ones(Steps,1);
z = 2;
s(1) = (alpha*a(1).^z+(1-alpha)*b(1).^z).^(1/z-1).*alpha.*a(1).^(z-1);
for t=2:Steps
b(t) = (gs+h(t-1))*b(t-1);
a(t) = (gm+v(t-1))*a(t-1);
s(t) = (alpha*a(t).^z+(1-alpha)*b(t).^z).^(1/z-1).*alpha.*a(t).^(z-1);
end
% After you calcualte s, select the values that you want to be the first and end values of vector
% and calculate the difference
s_1 = 0.3;
s_T = 0.7;
Error = norm([s(1),s(end)]-[s_1,s_T]);
if getSValues % This is for latter get the s vector
Error = s;
end
end
For this function I get following results:
x =
0.4844 2.4731 -0.5938
fval =
0.0053
S_first_and_final =
0.3036 0.6960
Where x contains the values from alpha, gm and gs, fval is the error that you quantify and the s vector values are pretty close to 0.3 and 0.7.

Giuseppe Pintori

### Giuseppe Pintori (view profile)

on 14 Oct 2019
Thanks a lot

Sign in to comment.