Matlab,Matrix操作

时间:2013-08-12 11:58:46

标签: performance matlab indexing

我有例如尺寸为50 * 50的其他矩阵A的索引矩阵a。

 2    21     1
 2    41     1
 2    47     1
 2    50     1

我希望在每个步骤中乘以例如第1行

A(2,21)* A(21.1)
第2行

A(2,41)* A(41,1)


所以,我使用这段代码

for i=1:nrow
c=ncol;
   if c~=1
   mul(i)=mul(i)*A(a(i,c-1),a(i,c));
   c=c-1;
   end
end

是否有更高效的代码?

3 个答案:

答案 0 :(得分:3)

您可以使用sub2indprod

来实现这一目标
mul=prod(A(sub2ind(size(A),a(:,1:end-1), a(:,2:end))),2);

答案 1 :(得分:1)

调用你的索引矩阵I,尝试这样的事情:
mul = A(I(:,1),I(:,2)) * A(I(:,2),I(:,3))并查看matlab是否可以为您优化它 我在matlab表示法中相当生疏,所以请原谅这句话是否明确无效。

编辑:我想我并不完全明白你想要完成的是什么。

答案 2 :(得分:1)

一般内容:A(sub2ind(size(A), I(:, 1), I(:, 2))).*A(sub2ind(size(A), I(:, 2), I(:, 3)))

例如:

 I= [2    5     1;
 2    4     1;
 2    3     1;
 2    1     1]

 A= rand(5, 5)


A(sub2ind(size(A), I(:, 1), I(:, 2))).*A(sub2ind(size(A), I(:, 2), I(:, 3)))
相关问题