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

7 ビュー (過去 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 Center および File ExchangeLoops 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