MATLAB Answers


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

Asked by Maria Galle on 14 Sep 2019
Latest activity Commented on by Steven Lord
on 15 Sep 2019
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 Comment

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.

Sign in to comment.

1 Answer

Answer by Jackson Burns on 15 Sep 2019

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)


Sign in to comment.