필터 지우기
필터 지우기

Find the sum of the non perimeter elements of a matrix using a for loop

조회 수: 2 (최근 30일)
I have this matrix
B=[-3 4 7;9 11 -13;-17 19 -23;-29 31 37;39 41 47]
and I need to find the sum of the non perimeter elements using a for loop. I can find the sum of a single column or row or of the whole matrix, but I don't know how to write a loop to only sum the 3 non perimeter numbers. Any help is appreciated, thank you.

채택된 답변

Image Analyst
Image Analyst 2016년 4월 24일
편집: Image Analyst 2016년 4월 24일
Try it this way:
B=[-3 4 7;9 11 -13;-17 19 -23;-29 31 37;39 41 47]
[rows, columns] = size(B)
theSum = 0;
for col = 2 : columns - 1
for row = 2 : rows-1
theSum = theSum + B(row, col);
end
end
fprintf('The sum = %f\n', theSum);
  댓글 수: 2
Vinny
Vinny 2016년 4월 24일
Thank you! How about if I wanted it to find the sum of the perimeter elements?
Image Analyst
Image Analyst 2016년 4월 24일
Hopefully you're not just asking me to do all your homework for you. Here is one way:
B=[-3 4 7;9 11 -13;-17 19 -23;-29 31 37;39 41 47]
[rows, columns] = size(B)
theSum = 0;
for col = 1 : columns
for row = 1 : rows
if row == 1 || row == rows || col == 1 || col == columns
% It's on the perimeter of the array.
theSum = theSum + B(row, col)
end
end
end
fprintf('The sum = %f\n', theSum);

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Azzi Abdelmalek
Azzi Abdelmalek 2016년 4월 24일
편집: Azzi Abdelmalek 2016년 4월 24일
A=B
A(:,[1 end])=0
A([1 end],:)=0
out=sum(A(:))

Ibrahim Abouemira
Ibrahim Abouemira 2019년 5월 19일

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by