Info

この質問は閉じられています。 編集または回答するには再度開いてください。

how can i genaralise this code for any m*n matrix?{the original question is to sum all the elements in the perimeter of a given matrix}?

1 回表示 (過去 30 日間)
Subramanian Mahadevan
Subramanian Mahadevan 2016 年 9 月 25 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
This was my code;which works good for a 3*3 matrix.
function sum1 = peri_sum(A);
q=0;r=0;s=0;t=0;u=0;v=0;w=0;
A=[1:3;4:6;7:9];
q = A([1,end],2);
r = A(:,[1,end]);
s = reshape(q,1,2);
t = reshape(r,1,6);
u=sum(s);
v=sum(t);
w=u+v;
sum1 = w;
end

回答 (2 件)

Image Analyst
Image Analyst 2016 年 9 月 25 日
Try this:
topSum = sum(A(1, 1:end))
bottomSum = sum(A(end, 1:end))
leftSum = sum(A(2:end-1, 1))
rightSum = sum(A(2:end-1, end))
perimeterSum = topSum + bottomSum + leftSum + rightSum
  4 件のコメント
Subramanian Mahadevan
Subramanian Mahadevan 2016 年 9 月 26 日
why is there a for loop for k?where is it being used?Is it possible to do it without using loops? and the matrix it didn't work for was [1 1;1 1].
Image Analyst
Image Analyst 2016 年 9 月 26 日
The loop was just to try different input matrices to make sure I didn't pick a sample test matrix that just happened to work.
So anyway, using [1,1;1,1], which has 1's all the way around the perimeter, and therefore has a sum of 4:
A = [1,1;1,1];
topSum = sum(A(1, 1:end));
bottomSum = sum(A(end, 1:end));
leftSum = sum(A(2:end-1, 1));
rightSum = sum(A(2:end-1, end));
perimeterSum = topSum + bottomSum + leftSum + rightSum
This gives perimeterSum = 4 as expected. So, you forgot to tell me what you expect the sum of the outer perimeter values of that to be. Obviously you don't think it's 4, but what do you think it should be, and why?

Andrei Bobrov
Andrei Bobrov 2016 年 9 月 26 日
a = randi(9,3,5)
s = size(a);
t = true(s);
t(2:end-1,2:end-1) = false(s-2);
out = sum(a(t));
  2 件のコメント
Subramanian Mahadevan
Subramanian Mahadevan 2016 年 9 月 26 日
this doesn't hold true for a 3*3 matrix [1 2 3;4 5 6;7 8 9]
James Tursa
James Tursa 2016 年 9 月 26 日
Andrei's code and your code give the same result for this A matrix, 40.

この質問は閉じられています。

Community Treasure Hunt

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

Start Hunting!

Translated by