# Matrix manipulation and using the sum command

1 view (last 30 days)

Show older comments

##### 0 Comments

### Answers (2)

John Chilleri
on 23 Jan 2017

Edited: John Chilleri
on 29 Jan 2017

Hello,

Would,

A(2,2) = 0;

A(2,2) = sum(A(:));

or

A(2,2) = sum(A(:)) - A(2,2);

suffice?

You could also generalize this to any matrix that has a center value (i.e. n x n where n is odd):

n = size(A,1);

A((n+1)/2,(n+1)/2) = sum(A(:)) - A((n+1)/2,(n+1)/2);

Hope this helps!

##### 2 Comments

John Chilleri
on 29 Jan 2017

Thanks for all the feedback on many of my posts! It's very helpful and much appreciated!

I decided to test if sum(A(:)) is faster than sum(sum(A))!

Other than being more elegant, it's also faster; performing 1,000,000 sum(A(:)) took about ~1.4 seconds versus ~2.2 seconds for sum(sum(A)). Will switch to A(:) from here on out!

Walter Roberson
on 30 Jan 2017

Edited: Walter Roberson
on 30 Jan 2017

If you are doing this over an entire matrix, use

conv2(A, [1 1 1; 1 0 1; 1 1 1], 'same')

to do everything at once.

##### 0 Comments

### See Also

### Categories

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!