Matlab: Access matrix elements using indices stored in other matrices

℡╲_俬逩灬. 提交于 2019-12-11 06:48:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!