Subs Error while using solve function

Hello!
I have question about using solve function.
I'm trying to derive yield to maturity using forward contract prices.
During the process, I tried to use solve function as shown below, which gives me error about
not able to transform data into double and recommending usage of 'subs' function.
I think i am doing this in the worst way possible, so Could you please give me the solution about this error?
Thanks.
T = rows(Data_full);
yield = zeros(T,1);
syms R P
for t = 1:T
eqn = (5/2)/(1+(R/2))+(5/2)/(1+(R/2)^2)+(5/2)/(1+(R/2)^3)+(5/2)/(1+(R/2)^4)+(5/2)/(1+(R/2)^5)...
+(5/2)/(1+(R/2)^6)+100/(1+(R/2)^6) == P;
P = Data_full(t,1);
yield(t) = solve(eqn,R);
end
yield

Answers (2)

Allocate the value to P before defining the equation solve().
T = rows(Data_full);
yield = zeros(T,1);
syms R P
for t = 1:T
%Define the value for P
P = Data_full(t,1);
%Equation to solve for
eqn = (5/2)/(1+(R/2))+(5/2)/(1+(R/2)^2)+(5/2)/(1+(R/2)^3)+(5/2)/(1+(R/2)^4)+(5/2)/(1+(R/2)^5)...
+(5/2)/(1+(R/2)^6)+100/(1+(R/2)^6) == P;
%Solution
yield(t) = solve(eqn,R);
end
yield
Or you can directly use the value, no need to define P -
T = rows(Data_full);
yield = zeros(T,1);
syms R
for t = 1:T
%Equation to solve for
eqn = (5/2)/(1+(R/2))+(5/2)/(1+(R/2)^2)+(5/2)/(1+(R/2)^3)+(5/2)/(1+(R/2)^4)+(5/2)/(1+(R/2)^5)...
+(5/2)/(1+(R/2)^6)+100/(1+(R/2)^6) == Data_full(t,1);
%Solution
yield(t) = solve(eqn,R);
end
yield
You will have to find criteria to sort out the solution you want. E.g. for real solutions only you could use
syms R
P = 10;
eqn = (5/2)/(1+(R/2))+(5/2)/(1+(R/2)^2)+(5/2)/(1+(R/2)^3)+(5/2)/(1+(R/2)^4)+(5/2)/(1+(R/2)^5)...
+(5/2)/(1+(R/2)^6)+100/(1+(R/2)^6) == P;
SOL = double(solve(eqn,R))
SOL =
1.6229 - 1.1718i 1.6229 + 1.1718i -1.4316 - 1.4125i -1.4316 + 1.4125i 1.4324 - 1.4129i 1.4324 + 1.4129i -0.6115 - 1.9172i -0.6115 + 1.9172i 1.0190 - 1.7650i 1.0190 + 1.7650i -2.3857 - 0.0221i -2.3857 + 0.0221i 1.4932 - 2.4597i 1.4932 + 2.4597i -1.4304 - 2.5567i -1.4304 + 2.5567i 3.0832 + 0.0000i
SOL = SOL(abs(imag(SOL))<1e-5)
SOL = 3.0832

Categories

Asked:

on 26 Dec 2023

Edited:

on 26 Dec 2023

Community Treasure Hunt

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

Start Hunting!