How to print the diagonals of a matrix as shown below.
4 views (last 30 days)
Show older comments
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 Comments
Image Analyst
on 19 Oct 2018
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.
Accepted Answer
possibility
on 19 Oct 2018
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 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!