Subs Error while using solve function
Show older comments
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)
Dyuman Joshi
on 26 Dec 2023
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
1 Comment
Dyuman Joshi
on 26 Dec 2023
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 = SOL(abs(imag(SOL))<1e-5)
Categories
Find more on Systems of Nonlinear Equations 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!