Error using sum, interpn and ndgrid: Arrays have incompatible sizes for this operation
3 次查看(过去 30 天)
显示 更早的评论
I am using MATLAB R2021b. I have a stochastic dynamic programming problem that I'm trying to solve by value function iteration (VFI). I want to solve for V in:
My endogenous state variable is , my exogenous state variables are P and ϵ and my choice variable is s (ϵ is random). have defined a grid of values for the states. I am interpolating the value function through ndgrid but when I try to find the expected value of the value function I get the following error. This is my code:
% state space
p_vec=linspace(0.5,5,50)';
epsilon_vec = linspace(0.5,2.5,3)'; % epsilon has 3 states
s_vec = linspace(sbar,15,100)';
% a finer state space for interpolation
pp = linspace(0.5,5,100)';
epep = linspace(0.5,2.5,20)';
ss = linspace(sbar,15,200)';
% grids for interpolation
[p_grid,epsilon_grid,s_grid] = ndgrid(p_vec,epsilon_vec,s_vec);
[pp_grid,epep_grid, ss_grid] = ndgrid(pp,epep,ss);
% transition matrix for epsilon
pi=[0.3,0.4,0.3;0.25,0.25,0.5;0.7,0.22,0.08]; % pi(i,j) = Pr(next period state is j|today's state is i).
% so each row sums to 1
% initial guess for V
V0=zeros(length(p_vec),length(epsilon_vec),length(s_vec));
% other parameters
beta=0.95;
r=0.05;
% interpolate and calculating expected value of V
sum(pi(state_ep,:)*interpn(p_grid,epsilon_grid,s_grid,V0,pp_grid,epep_grid,ss_grid));
I am getting two errors. The first one is:
'Error using *
Arguments must be 2-D, or at least one argument must be scalar. Use TIMES (.*) for elementwise multiplication"
So I changed the code to:
sum(pi(state_ep,:).*interpn(p_grid,epsilon_grid,s_grid,V0,pp_grid,epep_grid,ss_grid));
This produced the following error:
"Arrays have incompatible sizes for this operation."
Where am I going wrong?
0 个评论
回答(1 个)
Jan
2022-11-9
It is a bad idea to redefine "pi" as variable, because this conflicts with the constant pi.
Use the debugger to examine the problem. Type this in the command window:
dbstop if error
Then run the code again. When Matlab stops at the error, check the sizes of the used variables:
size(sum(pi(state_ep,:)))
size(interpn(p_grid, epsilon_grid, s_grid, V0, pp_grid, epep_grid, ss_grid))
Now decide, which kind of multiplication you want. Just trying * or .* because an error occurs is "gunshot programming". Prefer to convert your intentions to the correct operator instead of changing the code until no error occurs.
2 个评论
Jan
2022-11-10
@Saunok Chakrabarty: There is no need to apologize. Your questions about Matlab are welcome and they are the purpose of this forum. I'm glad if I could assist you a little bit to find the source of the problem.
另请参阅
类别
在 Help Center 和 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!