简体   繁体   中英

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 . 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 .

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.

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 . 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 .

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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