繁体   English   中英

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

[英]MATLAB indexing by indexes in another matrix

我正在尝试根据存储在另一个矩阵中的索引值生成一个新矩阵。

这对于 for 循环来说是微不足道的,但这是目前我正在尝试优化的某些代码中最慢的一行,所以我正在寻找一种没有循环的方法,并将我的头发拉出来。 我敢肯定这已经被回答过,而且我只是不知道正确的搜索词。

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

我假设您的代码中n1的值比您提供的示例中的值大得多,这可以解释为什么它“慢”。

为了在没有循环的情况下执行此操作,您可以使用 线性索引

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)

经过的时间是 1.309654 秒。

经过的时间是 0.062549 秒。

答案=

合乎逻辑的

1

尝试这个:

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

这是时间:

Elapsed time is 0.000517 seconds.

暂无
暂无

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

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