Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Nearly diagonal matrix

  1. Nov 16, 2008 #1
    I am trying to create the following Matrix without the use of a for loop.
    1 2 1 0 0 0 0 0 0 0 0 0
    0 0 1 2 1 0 0 0 0 0 0 0
    0 0 0 0 1 2 1 0 0 0 0 0
    0 0 0 0 0 0 1 2 1 0 0 0
    Etc.
    Is there a simple way of doing this

    Edit: Using Matlab
     
    Last edited: Nov 16, 2008
  2. jcsd
  3. Nov 16, 2008 #2

    f95toli

    User Avatar
    Science Advisor
    Gold Member

    Are you using Matlab?
    You have a tridiagonal matrix so the easiest way to set it up is to add 3 diagonal matrices.

    If you have an m-by-m matrix you can write

    diag(2*ones(1,m),0) + diag(ones(m-1,1),1) + diag(ones(m-1,1),-1)


    Note that this matrix will have a 2 at the first and last position of the main diagonal, but you can easily remove the first and last row.
     
  4. Nov 16, 2008 #3
    Well It isn't tridiagonal because every row is shifted to the left by one .
     
  5. Nov 17, 2008 #4
    Simply cannot resist the opportunity for me to practise writing a matlab script :biggrin:


    % will display m by n matrix B that wrapped the elements 1 2 1

    m=5; n=10;
    A=zeros(1,n);
    A(1)=1; A(2)=2; A(3)=1;

    for k=1:m
    B(k,:)=circshift(A,[1 k-1]);
    end
    B
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?