How to print the diagonals of a matrix as shown below.

조회 수: 14 (최근 30일)
Evan Mellish
Evan Mellish 2018년 10월 19일
댓글: possibility 2018년 10월 19일
This is my code to create the matrices shown.
%Part a
prompt1= 'What is the n value?';
prompt2= 'What is the m value?';
n= input(prompt1);
m=input(prompt2);
A=zeros(n,m);
for i=1:n
for j=1
A(i,j)=1;
end
end
for i=1:n
for j=1:m
if(i<2)
A(i,j)=1;
else if (j<2)
A(i,j)=1;
end
end
end
end
for i=2:n
for j=2:m
A(i,j)= A(i,j-1)+ A(i-1,j);
end
end
A
I understand that "diag" can be used to display the diagonal of a matrix. However I do not know how to either print the diagonals that go up and to the right.
  댓글 수: 2
madhan ravi
madhan ravi 2018년 10월 19일
upload your code
Image Analyst
Image Analyst 2018년 10월 19일
Looks very much like homework. So I've tagged it as such. Please read this link so we can give you hints and guide you towards the answer since we can't give you the answer outright or you'd get in trouble with your instructor.

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

채택된 답변

possibility
possibility 2018년 10월 19일
Since it looks like an assignment, I'd like to propose some approaches rather than giving the exact answer to do it.
One exhaustive way to do it: After generating the matrix, you may select a row, add the first element into an empty array. Then go up and right, add the element into the array. Do it in a for loop until you reach the up-edge of the matrix. Create another loop to scan all rows. Then in the second column, add the last element, do the same procedure till you hit the right edge. Scan all remained columns.
Another way by sliding the matrix: Select the left-up corner element. Start increasing the size of the matrix by both column and rows at the same time. Use diag to collect the diag elements.
There may be different ways, of course.
  댓글 수: 2
Evan Mellish
Evan Mellish 2018년 10월 19일
Is it possible to have multiple statements in the initialization of a for loop? Ex. for x=0; x<=b-1 ...
possibility
possibility 2018년 10월 19일
No, but that can be handled by creating a for loop within a for loop.

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by