How to create a nxn matrix by using for-end loop?

조회 수: 3 (최근 30일)
Maria Galle
Maria Galle 2019년 9월 14일
댓글: Steven Lord 2019년 9월 15일
How do I:
Create a n × n matrix of n = 20 by using for-end loop such that the matrix has diagonal elements of a value 2. The elements right next to the diagonal elements have their values of 1. The other elements are zeros.
  댓글 수: 1
Steven Lord
Steven Lord 2019년 9월 15일
This sounds like it's a homework assignment. If it is, show us what you've written so far to try to solve the problem and ask a specific question about where you're experiencing difficulty and we may be able to offer some guidance.

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

답변 (1개)

Jackson Burns
Jackson Burns 2019년 9월 15일
You can do it using diag and avoid the for loop altogether.
mymat = diag(ones(19,1),-1) + diag(zeros(20,1)+2,0) + diag(ones(19,1),1)

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by