MathLover
MathLover

Reputation: 75

Using the solve function in Matlab

I need to solve a non-linear equation in matlab. Please see the code for details.

sigma = .25;
beta = 2;
alpha = .1;
eta = .025;

syms x

phi = sqrt(2.*sigma.^2 + beta.^2);
kappa = (beta + phi)./(beta - phi);

w = .5;

D is imported data;

A = @(t) exp((alpha*(beta+phi).*t)./sigma.^2).*...
    ((1-kappa)./(1-kappa.*exp(phi.*t))).^(2.*alpha./sigma.^2);

B = @(t) (beta - phi)./sigma.^2 + 2.*phi./(sigma.^2.*(1-kappa.*exp(phi.*t)));

C = @(t) exp(eta^2.*t^3/6);

G = @(t) (alpha./phi).*(exp(phi.*t)-1).*exp(alpha.*(beta+phi).*t./sigma^2).*...
    ((1-kappa)./(1-kappa.*exp(phi.*t))).^((2.*alpha./sigma^2) + 1);

H = @(t) exp((alpha.*(beta+phi) + phi.*sigma^2)./sigma^2).*...
   ((1-kappa)./(1-kappa.*exp(phi.*t))).^((2.*alpha./sigma^2) + 2);

spread_prot_portion = @(i,j,t) exp(B(t).*x).*D(i,j).*(G(t) + H(t).*x);
spread_fee_portion  = @(i,j,t) A(t).*exp(B(t).*x).*D(i,j);

t = (.5:.5:10);
j = (1 :1 :20);
k = 1:20


solve('cds(1)- w*sum(spread_prot_portion(1,j(k),t(k)))/sum(spread_fee_portion(1,j(k),t(k))) = 0')

Note that cds is loaded data. I need to solve for x. That is why it is the only variable in syms and all other variable are given. unfortunately for the sums I cannot just write out an expression. Some help would be greatly appreciated

Upvotes: 0

Views: 1097

Answers (1)

Strategy Thinker
Strategy Thinker

Reputation: 363

For a situation like this you need to use a for loop to find the sum. Suppose

syms x;
f = @(i, j) i + j + x;

then to sum over all indices of i and j you need

total = 0;
for i = 1:10
  for j = 1:10
    total = total + f(i, j);
  end
end
display(total) %// total = 100*x + 1100

then to solve for total = 100 you write (note the lack of apostrophes)

xSol = solve(total - 100);

Note however, you are trying to find the exact solution to a very difficult problem. It may be better to use fsolve, with

xSol = fsolve(@fun, estimateOfx);

where fun the function that calculates the sum of f(i,j) for a specific value of x, i.e.

function total = fun(x)
f = @(i, j) i + j + x;
%// Find total as above
end

Here is an example where explained fsolve a little bit more.

Upvotes: 0

Related Questions