MATLAB Create Matrix without For Loop in MatLab

AI Thread Summary
Creating a specific matrix in MATLAB without using a for loop can be achieved by leveraging diagonal matrices. The desired matrix features a pattern with 1s and 2s arranged in a tridiagonal structure, where each row is shifted to the left. The solution involves using the `diag` function to construct the matrix. Specifically, for an m-by-m matrix, the expression `diag(2*ones(1,m),0) + diag(ones(m-1,1),1) + diag(ones(m-1,1),-1)` generates the base structure. However, this method results in a 2 at the first and last positions of the main diagonal, which can be adjusted by removing the first and last rows. Additionally, a MATLAB script utilizing `circshift` is provided to display the matrix while maintaining the desired pattern without explicitly using loops.
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
 
Back
Top