Matlab的:使用索引访问矩阵元素存储在其它基质(Matlab: Access matrix el

2019-10-20 04:35发布

我在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行的方式,但我写的要清楚我想要什么。

Answer 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;


文章来源: Matlab: Access matrix elements using indices stored in other matrices