Index in position _ exceeds array bound when executing function, but not when running interactively

1 view (last 30 days)
I wrote the following function:
function f = ll_func(theta)
global cover premium draws cost
% Extract input parameters
alpha = theta(1);
beta = theta(2);
mu = theta(3);
sigma = theta(4);
delta = theta(5);
% Demand probabilities
eu = beta*cover + alpha*premium + mu + sigma*draws; % Expected utility of each plan
num = exp(eu);
denom = sum(num, 5);
demprob = num./denom;
% Cost probabilities
meandraws = mean(draws(:,:,:,:,1:5), 1);
costprob = normpdf(cost - delta - sigma*meandraws);
costprob = costprob(1,:,:,:,:);
% Log-likelihood
demside = sum(log(mean(prod(prod(demprob.^choice, 5), 4), 2)), 'all');
supside = sum(log(mean(prod(costprob, 4), 2)), 'all');
f = -(demside + supside);
end
When I run
theta = [-1;1;1;2;3];
ll_func(theta);
I get the error
Index in position 5 exceeds array bounds (must not exceed 1).
Error in ll_func (line 19)
meandraws = mean(draws(:,:,:,:,1:5), 1);
but when I run the code in ll_func.m interactively it doesn't throw this error. What is going on here?

Accepted Answer

Matt J
Matt J on 27 Sep 2020
Edited: Matt J on 27 Sep 2020
What's going on is size(draws,5)=1. You have passed in data whose dimensions are not what the code expects. This may be connected with the fact that you are using global variables, which is usually unrecommended - if draws was changed somehow in the base workspace between runs by another function, it is harder to see.
  4 Comments
Matt J
Matt J on 27 Sep 2020
Edited: Matt J on 27 Sep 2020
When I pause execution at line 19 in ll_func,
I find that draws and the other global variables are empty:
K>> whos cover premium draws cost
Name Size Bytes Class Attributes
cost 0x0 0 double global
cover 0x0 0 double global
draws 0x0 0 double global
premium 0x0 0 double global
This happens because they are not declared as global in the workspace of eio1ass2.m.

Sign in to comment.

More Answers (0)

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!