问题
I am working in matlab. I have five matrices in ,out, out_temp,ind_i , ind_j, all of identical dimensions say n x m. I want to implement the following loop in one line.
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
It is assured that the values in ind_i lies in range 1:n and values in ind_j lies in range 1:m.
I believe a way to implement line 3 would give the way to implement line 4 , but I wrote it to be clear about what I want.
回答1:
Code
%// 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;
来源:https://stackoverflow.com/questions/23903815/matlab-access-matrix-elements-using-indices-stored-in-other-matrices