error due to function handle in for loop
显示 更早的评论
Hi! I have a problem with my optimization problem. I try to minimize the difference between real option price and model option price (Its an option pricing model calibration). I use the for loop to catch every option in my dataset in the fmincon optimization to optimize the summed error of 'real' and 'model' price.
The code looks like this:
The "cl_heston()" is the pricing formla for the model price and works when inserting random numbers instead of x.
'Testset4' is the set with the information for the option price calculation
real is the actual historical price.
%Optimierung Heston Loop
clc
clear
global data;
x0 = [0.5 0.5 1 -0.5 1]; % starting values
lb = [0 0 0 -1 0]; % lower bound
ub = [1 1 6 1 20]; % upper bound
data = xlsread('Testset4');
for n = 1:length(data)
model(n) = @(x) cl_heston(data(n, 1), x(1), x(2), x(5), x(3), data(n, 4), 0, x(4), data(n, 2), data(n, 3)); % model price
real(n) = data(n, 5); % historical price
end
objective = @(x) sum(abs(real-model(x))); % objective function
%fmincon Funktion
x = fmincon(objective, x0, [], [], [], [], lb, ub, []);
objective(x)
When I run it I receive the error: Nonscalar arrays of function handles are not allowed; use cell arrays instead.
If I remove the '(n)' from 'model (n)' it works but just takes the last number in the dataset for the model price for every iteration.
Any help is highly appreciated!
3 个评论
Mohammad Sami
2020-1-23
编辑:Mohammad Sami
2020-1-23
What if you used arrayfun in objective
objective = @(x) sum( abs( arrayfun( @(y,z)y-z(x),real,model) ) );
Jonas Huwyler
2020-1-23
Walter Roberson
2020-1-23
model{n} = @(x) cl_heston(data(n, 1), x(1), x(2), x(5), x(3), data(n, 4), 0, x(4), data(n, 2), data(n, 3)); % model price
Question for you:
objective = @(x) sum(abs(real-model(x))); % objective function
%f
Is that indexing your hypothetical vector of function handles at location x? Or is it invoking the vector of function handles with argument x? If so then what does it mean to invoke a vector of function handles?
回答(1 个)
Jonas Huwyler
2020-1-23
0 个投票
1 个评论
Walter Roberson
2020-1-23
With model being a cell array, model(x) would be attempting to index the cell array at location x
I suggest that you replace model(x) with
cellfun(@(F) F(x), model)
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!