Matlab 矢量化 for 循环(网格取决于循环索引)

问题描述 投票:0回答:1

我必须在第一维上对 3-D 数组 V(e,b,d) 进行最大化,获得我称之为 e_opt 的东西,它将是一个 b*d 矩阵,即

e_opt(b,d) = argmax_e {V(e,b,d)}

非标准特征是 e 的网格取决于 d。所以我无法消除 d 上的循环,我需要加快代码速度。我附上 MWE,以便事情变得清晰。在我的电脑上,它运行大约 1 秒,但这太慢了,因为我必须这样做很多次。 非常感谢任何帮助!

clear
close all
clc
rng("default")

% Size of grids
n_b = 1000;
n_d = 1000;
n_e = 5000;

% Parameters
delta   = 0.2696037674949296; 
%omega_0 = 0.0015534835229589;
%omega_1 = 0.0013023827114628;

% Generate fake data
cost_mat = rand(n_e,n_d);
prob_mat = rand(n_e,n_d);
option_nob = rand(n_b,1);
d_grid = linspace(0,2.3,n_d)';

%% Create a grid for "e". The non-standard feature is that the upper bound
% of the e_grid depends on "d"
e_grid_mat = zeros(n_e,n_d);
e_min = 0;
space = 1.5;
for d_c=1:n_d
    d_val = d_grid(d_c);
    e_max = 0.1+0.2*d_val; %silly example, don't take this literally
    % e_grid is NOT equally spaced
    e_grid_mat(:,d_c) = e_min+(e_max-e_min)*(linspace(0,1,n_e).^space)';
end

%% The code below is the part that I'd like to speed up
tic
e_opt = zeros(n_b,n_d);
for d_c = 1:n_d
    % Effort grid depends on d (upper bound changes, but same no. of elements)
    e_grid = e_grid_mat(:,d_c); %each column of e_grid_mat is different!
    % V(e,b) has dim: (n_e,n_b) and I maximize with respect to the first dimension, e
    V = -cost_mat(:,d_c)-delta*prob_mat(:,d_c).*option_nob';
    [~,max_ind] = max(V,[],1); %maxind is (1,n_b) vector
    e_opt(:,d_c)  = e_grid(max_ind);
end %end d
toc

%To check results
disp(mean(mean(e_opt)))
matlab for-loop vectorization
1个回答
0
投票

e
的值范围取决于
d
这一事实并不妨碍以矢量化方式计算最大化e
index
。网格的不均匀性仅在从索引中检索 e 的最大化
values
时才会产生影响;但这可以使用线性索引很容易地完成。

因此,代码的最后一部分就变成了

V = -cost_mat-delta*prob_mat.*reshape(option_nob, 1, 1, []); % compute the full V
[~, max_ind] = max(V,[],1); % indices of maxima along the first dimension
max_ind = permute(max_ind, [2 3 1]); % remove singleton dimension
max_ind = max_ind + (0:size(V,2)-1).'*size(V,1); % apply linear indexing
e_opt = e_grid_mat(max_ind).'; % retrieve maximizing values

代码现在已矢量化,但请考虑到这并不总是会带来显着的加速。

© www.soinside.com 2019 - 2024. All rights reserved.