Error using sum, interpn and ndgrid: Arrays have incompatible sizes for this operation

조회 수: 4(최근 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
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
% other parameters
% interpolate and calculating expected value of V
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:
This produced the following error:
"Arrays have incompatible sizes for this operation."
Where am I going wrong?


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(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.

댓글을 달려면 로그인하십시오.


Find more on Mathematics 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!

Translated by