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.
0 件のコメント
採用された回答
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 件のコメント
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
2016 年 4 月 24 日
編集済み: Azzi Abdelmalek
2016 年 4 月 24 日
A=B
A(:,[1 end])=0
A([1 end],:)=0
out=sum(A(:))
0 件のコメント
Ibrahim Abouemira
2019 年 5 月 19 日
Hello,
Here's a function that performs your required task.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Multidimensional Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!