简体   繁体   English

MATLAB按另一个矩阵中的索引进行索引

[英]MATLAB indexing by indexes in another matrix

I'm trying to generate a new matrix, based on index values stored in another matrix.我正在尝试根据存储在另一个矩阵中的索引值生成一个新矩阵。

This is trivial to do with a for loop, but this is currently the slowest line in some code I'm trying to optimise, and so I'm looking for a way to do it without the loop, and pulling my hair out.这对于 for 循环来说是微不足道的,但这是目前我正在尝试优化的某些代码中最慢的一行,所以我正在寻找一种没有循环的方法,并将我的头发拉出来。 I'm sure this has been answered before, and that I just don't know the right search terms.我敢肯定这已经被回答过,而且我只是不知道正确的搜索词。

n1 = 10;
n2 = 100;

a = randi(n2,[1,n1]);
b = randi(n2,[4,n1]);
c = rand(100,100);

for i = 1:n1
    d(:,i) = c(a(i),b(:,i));
end

I'm assuming the value of n1 in your code is way bigger than in the example you provide, which would explain why it is "slow".我假设您的代码中n1的值比您提供的示例中的值大得多,这可以解释为什么它“慢”。

In order to do this without a loop, you can use Linear indexing :为了在没有循环的情况下执行此操作,您可以使用 线性索引

n1 = 1e6;
n2 = 100;

a = randi(n2,[1,n1]);
b = randi(n2,[4,n1]);
c = rand(n2,n2);

% With a loop
d = zeros(4,n1);
tic

for i = 1:n1
    d(:,i) = c(a(i),b(:,i));
end

toc

% A faster way for big values of `n1`
d2 = zeros(4,n1);
tic

a_rep = repmat(a,4,1); % Repeat row indexes to match the elements in b

idx_Lin = sub2ind([n2,n2],a_rep(:),b(:)); % Get linear indexes

d2(:) = c(idx_Lin); % Fill

toc

isequal(d,d2)

Elapsed time is 1.309654 seconds.经过的时间是 1.309654 秒。

Elapsed time is 0.062549 seconds.经过的时间是 0.062549 秒。

ans =答案=

logical合乎逻辑的

1 1

Try This:尝试这个:

n1 = 10;
n2 = 100;
a =  randi(n2,[1,n1]);
b =  randi(n2,[4,n1]);
c = rand(100,100);
idx = (1:n1);
tic
d1=(c(a(idx),b(:,idx)))';
[idx,idy]=meshgrid(0:44:400,1:4);
d1=d1(idy+idx);
toc

this is the timeing:这是时间:

Elapsed time is 0.000517 seconds.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM