How can I find the sum of the perimeter of a matrix?

2 ビュー (過去 30 日間)
Alexandra Huff
Alexandra Huff 2016 年 8 月 5 日
回答済み: Ibrahim Abouemira 2019 年 5 月 19 日
Hi, I am wondering if I had a matrix [1,2,3;1,2,3;1,2,3] how I could find the sum of the perimeter. Thanks an advance.

採用された回答

dpb
dpb 2016 年 8 月 5 日
One way amongst any number...
>> M=[1,2,3;1,2,3;1,2,3];
>> I=ones(size(M)); I(2:end-1,2:end-1)=0;
>> S=sum(reshape(M.*I,1,[]))
S =
16
>>

その他の回答 (3 件)

Stephen23
Stephen23 2016 年 8 月 5 日
編集済み: Stephen23 2016 年 8 月 5 日
In one line is easy and very fast:
>> M = [1,2,3;1,2,3;1,2,3];
>> sum(sum([M([1,end],2:end-1),M(1:end,[1,end]).']))
ans = 16
  5 件のコメント
dpb
dpb 2018 年 2 月 10 日
[ ... Ricardo Florez Answer moved to comment since was a follow-up question on earlier Answer syntax ... dpb]
Hi. Why is it necessary to write two "sum" in the code: sum(sum(M(...)? Please see below:
the sum(M(:))-sum(sum(M(2:end-1,2:end-1)))
Thank you.
dpb
dpb 2018 年 2 月 10 日
編集済み: dpb 2018 年 2 月 11 日
Because sum(M(2:end-1,2:end-1)) is a row vector of the sums of the columns in the submatrix; to get the total have to then add those values. This is taken care of in the first sum by the use of the special syntax (:) that returns all elements of an array/matrix in a column so sum only needs to add the one column vector. There is no syntax in Matlab to apply the secondary indexing operation to the result of the first function call return; there've been many suggest the enhancement.

サインインしてコメントする。


Sanjay Zamindar
Sanjay Zamindar 2018 年 6 月 28 日
編集済み: dpb 2018 年 6 月 28 日
function final_sum = peri_sum(A)
size_row = size(A,1)
size_col=size(A,2)
Sum_of_first_row = sum (A(1, [1:1:end])); %base
Sum_of_first_Colmn = sum(A([2:1:size_row],1))
%sum_col= sum(A([2:1:size_col], [1:size_col:size_col]));
Sum_of_last_column= sum(A([2:1:size_row],size_col))
sum_of_last_row = sum(A(size_row,[2:1:size_col-1]))
final_sum = sum_of_last_row+ Sum_of_last_column+Sum_of_first_Colmn+Sum_of_first_row
end

Ibrahim Abouemira
Ibrahim Abouemira 2019 年 5 月 19 日

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by