My code on n consecutive elements in a matrix

조회 수: 5 (최근 30일)
N/A
N/A 2018년 7월 11일
편집: Matt J 2018년 7월 11일
Hi, I got a question to figure out the largest sum of n consecutive elements in a matrix. The order can be in the same row, column, diagonal, or reverse diagonal. Here is my code. However, the matlab keeps telling me variables "i","j", "u", "w","z" may be unused.Could you give me a hint how to make these variables valid? Also, I guess there is a way to simply my code a little bit? Thanks!
A numerical example would be: Suppose A=[1 2; 3 4] and n=2. We need to find the largest sum of 2 consecutive elements in all directions. In this case, we have
rows: 1+2, 3+4
columns: 1+3, 2+4
diagonal: 1+4
reverse diagonal: 2+3
Obviously, the output of this function should be 3+4. How could I write a function without loops? Any hint will be appreciated.
% function x=maxsum(A, n)
[p,q]=size(A);
k=zeros(1,q*floor(p/n));
%rows
for i =1:p
j=1:q-n+1;
u=1:q*floor(p/n);
k(u)=sum(A(i,j:j+n-1));
i=i+1;
j=j+1;
u=u+1;
end
K=max(k);
%columns
y=zeros(1,p*floor(q/n));
for w=1:q-n+1
v=1:q;
z=1:p*floor(q/n);
y(z)=sum(A(w:w+n-1, v);
w=w+1;
v=v+1;
z=z+1;
end
Y=max(y);
%diagonal
t=zeros(1,p-n+1);
for h=1:p-n+1
B=A(h:h+n-1,h:h+n-1);
t(h)=diag(B);
h=h+1;
end
T=max(t);
%reverse diagonal
m=zeros(1,p-n+1);
for o=1:p-n+1
c=flip(A(o:o+n-1,o:o+n-1));
m(o)=diag(c);
o=o+1;
end
M=max(m);
%compare all
x=max([M T Y K]);
% end
  댓글 수: 2
Shantanu Gontia
Shantanu Gontia 2018년 7월 11일
편집: Shantanu Gontia 2018년 7월 11일
You are changing the looping variable inside the loop itself. In a MATLAB for, you need not increment the looping variable inside the loop, it is done automatically.
In addition, you have written j=1:q-n+1; and also, k(u)=sum(A(i,j:j+n-1));. This is inconsistent as j is a vector.
KSSV
KSSV 2018년 7월 11일
Your loop index is replaced with same variable inside loop. This is not good code. YOu need to rethink. Give us a numerical example with data, you will get help and this task can be achieved without loop.

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

채택된 답변

Matt J
Matt J 2018년 7월 11일
편집: Matt J 2018년 7월 11일
To avoid loops, use convolution. For example
forwardDiags = conv2(yourMatrix,eye(3),'valid')
will compute all forward diagonal sums of length 3. Similarly,
reverseDiags = conv2(yourMatrix,fliplr(eye(3)),'valid')
will compute reverse diagonals, and so on.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by