Create Matrix without For Loop in MatLab

  • Context: MATLAB 
  • Thread starter Thread starter realanony87
  • Start date Start date
  • Tags Tags
    Diagonal matrix Matrix
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
3 replies · 3K views
realanony87
Messages
9
Reaction score
0
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:
Physics news on Phys.org
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.
 
Well It isn't tridiagonal because every row is shifted to the left by one .
 
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