[英]Construct a matrix in Matlab where each element is obtained by summing all other elements in the same row
I have a matrix A
of zeros and ones in Matlab of dimension MxN
. 我在矩阵
MxN
有一个零和一的矩阵A
I want to construct a matrix B
of dimension MxN
, where B(i,j)
is obtained by summing A(h,j)
for all h
different from i
. 我想构造一个尺寸为
MxN
的矩阵B
,其中B(i,j)
是通过对与i
不同的所有h
求和A(h,j)
获得的。
This is my current code 这是我当前的代码
A=randi([0 1],2097144,20); %2097144x20
B = @( )bsxfun(@minus,sum(A(:,2:end),2),A(:,2:end)); %2097144x20
timeit(B)
which takes approx. 这大约需要 0.5 sec.
0.5秒
Would you be able to suggest anything faster? 您可以更快地提出建议吗?
Edited question thanks to the comments below: the code is correct; 由于以下注释,已编辑的问题:代码正确; my explanation to it is wrong;
我对此的解释是错误的; the correct explanation is
正确的解释是
I have a matrix A
of zeros and ones in Matlab of dimension MxN
. 我在矩阵
MxN
有一个零和一的矩阵A
I want to construct a matrix B
of dimension MxN
, where B(i,j)
is obtained by summing A(i,h)
for all h
different from j
. 我想构造一个维度为
MxN
的矩阵B
,其中B(i,j)
是通过对与j
不同的所有h
求和A(i,h)
获得的。
I assume that you want to call the code a large number of times. 我假设您要多次调用该代码。 If you want to call it with many different matrices A, then as far as I can see, you are more or less out of luck - mex can help you somewhat - you may be able to speed it up by say a factor of 2 or 3 but you are basically memory bound.
如果您想使用许多不同的矩阵A调用它,那么据我所知,您或多或少地感到不走运-mex可以为您提供一些帮助-您也许可以将其提高2倍或3,但您基本上是受内存限制的。
If on the other hand you are doing something more subtle, then it depends on the specific problem at hand - perhaps you can use the parallel toolbox or the gpu. 另一方面,如果您正在做一些更细微的事情,则取决于当前的特定问题-也许您可以使用并行工具箱或gpu。
You code doesn't do what you have stated. 您的代码不执行您所说的。 You wanted to sum along the columns (across rows that is).
您想沿列(跨行)求和。 Moreover, why have you skipped the first column.
此外,为什么要跳过第一列。 As per your requirement, the correct line would be
根据您的要求,正确的行是
B = bsxfun(@minus,sum(A,1),A);
which is about 4 times as fast. 大约快4倍。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.