Matlab:使用存储在其他矩阵中的索引访问矩阵元素 [英] Matlab: Access matrix elements using indices stored in other matrices

查看:187
本文介绍了Matlab:使用存储在其他矩阵中的索引访问矩阵元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 matlab 中工作。我有五个矩阵 in,out,out_temp,ind_i,ind_j,所有相同的维度都是 n x m
$ b

  out =零(n,m)
out_temp =零(ind_i(i,j),ind_j(i,j))= in(ind_i(i,j))中的每一个元素(n,m)
对于i = 1:n
: 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 code> 1:M 。
我相信一种实现第3行的方法会给出实现第4行的方法,但是我写了一个清楚我想要的内容。方案

 %//一次计算线性指数使用来自ind_i和ind_j的所有索引
%//记住out和out_temp的大小不会超出
%// ind_i的最大值为行数和ind_j的最大值对于数
%//列
ind1 = sub2ind([nm],ind_i(:),ind_j(:))

%//初始化out_temp
out = zeros(n,m)
out_temp = zeros(n,m)

%//最后索引out和out_temp并赋值
%//使用来自in的标记值和标量值。 (ind1)= in(ind1);
out_temp(ind1)= some_scalar_value;


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.

解决方案

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;

这篇关于Matlab:使用存储在其他矩阵中的索引访问矩阵元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆