Matlab:使用存储在其他矩阵中的索引访问矩阵元素

时间:2014-05-28 05:58:10

标签: matlab for-loop matrix indexing vectorization

我在 matlab 工作。我有五个矩阵in ,out, out_temp,ind_i , ind_j,所有相同的维度都说n x m。我想在一行中实现以下循环。

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行的方法,但是我写了这篇文章以明确我想要的内容。

1 个答案:

答案 0 :(得分:1)

<强>代码

%// 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;