我在MATLAB工作。 我有五个矩阵in ,out, out_temp,ind_i , ind_j,
所有相同尺寸的说, nxm
。 我想实现一个行下面的循环。
out = zeros(n,m)
out_temp = zeros(n,m)
for i = 1:n
for j = 1:m
out(ind_i(i,j),ind_j(i,j)) = in(ind_i(i,j),ind_j(i,j));
out_temp(ind_i(i,j),ind_j(i,j)) = some_scalar_value;
end
end
它保证了在值ind_i
在于范围1:n
和值ind_j
在于范围1:m
。 我相信方式,可以实现3号线将给予落实第4行的方式,但我写的要清楚我想要什么。
码
%// Calculate the linear indices in one go using all indices from ind_i and ind_j
%// keeping in mind that the sizes of both out and out_temp won't go beyond
%// the maximum of ind_i for the number of rows and maximum of ind_j for number
%// of columns
ind1 = sub2ind([n m],ind_i(:),ind_j(:))
%// Initialize out and out_temp
out = zeros(n,m)
out_temp = zeros(n,m)
%// Finally index into out and out_temp and assign them values
%// using indiced values from in and the scalar value respectively.
out(ind1) = in(ind1);
out_temp(ind1) = some_scalar_value;