Matrix manipulation and using the sum command

조회 수: 7 (최근 30일)
Ataman Ugur
Ataman Ugur 2017년 1월 23일
편집: Walter Roberson 2017년 1월 30일
Hey guys I'm trying to use the "sum" command to replace the central value in a 3x3 matrix by the 8 surrounding values, but I need to exclude the central value from the summation. A=[8 8 8;8 7 8;8 8 8], I need to replace the 7 with the sum of the surrounding 8's using the "sum" command. Can anyone show me how to exclude the 7 from the command A(2,2)=sum(A(1:3,1:3))?

답변 (2개)

John Chilleri
John Chilleri 2017년 1월 23일
편집: John Chilleri 2017년 1월 29일
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
Jan
Jan 2017년 1월 29일
편집: Jan 2017년 1월 29일
+1, Or sum(A(:)).
John Chilleri
John Chilleri 2017년 1월 29일
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
Walter Roberson 2017년 1월 30일
편집: Walter Roberson 2017년 1월 30일
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.

카테고리

Help CenterFile Exchange에서 Linear Algebra에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by