Create Matrix without For Loop in MatLab

  • Context: MATLAB 
  • Thread starter Thread starter realanony87
  • Start date Start date
  • Tags Tags
    Diagonal matrix Matrix
Click For Summary

Discussion Overview

The discussion revolves around creating a specific matrix structure in MATLAB without using a for loop. The matrix features a pattern of numbers that shifts left in each subsequent row, and participants explore methods to achieve this using MATLAB functions.

Discussion Character

  • Technical explanation, Exploratory, Debate/contested

Main Points Raised

  • One participant seeks a method to create a matrix with a specific pattern without using a for loop.
  • Another participant suggests using diagonal matrices to construct a tridiagonal matrix, proposing the use of the `diag` function to achieve this.
  • A third participant challenges the characterization of the matrix as tridiagonal, noting that the rows are shifted left by one position, which alters the structure.
  • A fourth participant shares a MATLAB script that utilizes `circshift` to create the desired matrix, indicating a willingness to practice coding in MATLAB.

Areas of Agreement / Disagreement

Participants do not reach a consensus on the classification of the matrix as tridiagonal, and there are competing methods proposed for constructing the matrix without a for loop.

Contextual Notes

There is an assumption that the matrix structure is understood among participants, but the exact requirements for the matrix creation are not fully clarified. The proposed methods may depend on specific definitions of matrix types.

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
 

Similar threads

Replies
0
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K
Replies
10
Views
3K
Replies
7
Views
2K
  • · Replies 4 ·
Replies
4
Views
4K
  • · Replies 10 ·
Replies
10
Views
4K
  • · Replies 8 ·
Replies
8
Views
3K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K