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

4 visualizzazioni (ultimi 30 giorni)
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 Commenti
Image Analyst
Image Analyst il 19 Ott 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.

Accedi per commentare.

Risposta accettata

possibility
possibility il 19 Ott 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 Commenti
Evan Mellish
Evan Mellish il 19 Ott 2018
Is it possible to have multiple statements in the initialization of a for loop? Ex. for x=0; x<=b-1 ...
possibility
possibility il 19 Ott 2018
No, but that can be handled by creating a for loop within a for loop.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Prodotti


Release

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by