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

10 次查看(过去 30 天)
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 个评论
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 中查找有关 Operating on Diagonal Matrices 的更多信息

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by