从MATLAB矩阵中提取数据而无需for循环 [英] Extract data from MATLAB matrix without for-loop
问题描述
在MATLAB中,假设我有一个10 x 100的矩阵,称为M
.我想做的是提取此矩阵的特定索引,并以行矢量化的方式基于行索引立即对它们进行操作.
In MATLAB, let us say I have a 10 x 100 matrix, called M
. What I would like to do, is extract particular indicies of this matrix, and do an operation on them immediately, based on the row index, in a vectorized fashion.
例如,对于第一行,我想计算sum(M(1, 1:1:100))
.然后对于第二行,我想要sum(M(2, 1:2:100))
.对于第三行,我要sum(M(3, 1:3:100))
,依此类推.对于第十行,我当然要sum(M(10, 1:10:100))
.
For example, for the first row, I want to compute sum(M(1, 1:1:100))
. Then for row two, I want sum(M(2, 1:2:100))
. For row three, I want sum(M(3, 1:3:100))
, etc etc. For row ten, I have of course sum(M(10, 1:10:100))
.
我在for循环中有这个,但是我想看看是否有一种方法可以在没有for循环的情况下提取此数据.谢谢.
I have this in a for loop, but I want to see if there is a way to extract this data without a for loop. Thank you.
推荐答案
您可以尝试使用单线
S=arrayfun(@(n) sum(M(n,1:n:100)), 1:10)
或者,您可以预先创建稀疏矩阵
Alternatively, you can create a sparse matrix beforehand
A=sparse(100,10);
for n=1:10,
A(1:n:100, n)=1;
end
并通过以下方式求和
S=diag(M*A);
可以通过定义A=sparse(10,100)
和
S=sum(M.*A,2);
我快速的卧推
M=rand(10,100);
sz = size(M);
tic;
for k=1:10000,
for n=1:sz(1),
B(n)=sum(M(n,1:n:end));
end
end
toc
tic;
for k=1:10000,
B=arrayfun(@(n) sum(M(n,1:n:end)), 1:sz(1));
end
toc
tic;
for k=1:10000,
A=sparse(sz(2), sz(1));
for n=1:sz(1),
A(1:n:end, n)=1;
end
B=diag(M*A);
end
toc
tic;
A=sparse(sz(2),sz(1));
for n=1:sz(1),
A(1:n:end, n)=1;
end
for k=1:10000,
B=diag(M*A);
end
toc
tic;
A=sparse(sz(1),sz(2));
for n=1:sz(1),
A(n, 1:n:end)=1;
end
for k=1:10000,
B=sum(M.*A,2);
end
toc
返回
Elapsed time is 0.552470 seconds.
Elapsed time is 2.409102 seconds.
Elapsed time is 0.638072 seconds.
Elapsed time is 0.052246 seconds.
Elapsed time is 0.061893 seconds.
用于30 x 1000矩阵
for 30-by-1000 matrix
Elapsed time is 1.785664 seconds.
Elapsed time is 3.954034 seconds.
Elapsed time is 4.760436 seconds.
Elapsed time is 0.926118 seconds.
Elapsed time is 0.865330 seconds.
以及1000 x 100矩阵
and for 1000-by-100 matrix
Elapsed time is 51.389322 seconds.
Elapsed time is 63.443414 seconds.
Elapsed time is 68.327187 seconds.
Elapsed time is 29.056304 seconds.
Elapsed time is 1.147215 seconds.
这篇关于从MATLAB矩阵中提取数据而无需for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!