matlabmatrixdiagonalsymmetry

How to create a symmetric matrix where each row/column is a subset of a known vector


I have a 7*1 vector a = (1:7).'. I want to form a matrix A of size 4*4 from vector a such that the elements of a form the anti-diagonals of matrix A as follows:

A = [1 2 3 4;
     2 3 4 5;
     3 4 5 6;
     4 5 6 7]

I would like this to work for a general a, not just when the elements are consecutive integers.

I appreciate any help.


Solution

  • You can use hankel:

    n= 4;
    A= hankel(a(1:n),a(n:2*n-1))
    

    Other solution(expansion/bsxfun):

    In MATLAB r2016b /Octave It can be created as:

    A = a((1:4)+(0:3).')
    

    In pre r2016b you can use bsxfun:

    A = a(bsxfun(@plus,1:4, (0:3).'))
    

    Example input/output

    a = [4 6 2 7 3 5 1]
    
    A =
    
       4   6   2   7
       6   2   7   3
       2   7   3   5
       7   3   5   1
    

    Using the benchmark provided by @Wolfie tested in Octave:

     _____________________________________
    |Method   |memory peak(MB)|timing(Sec)|
    |=========|===============|===========|
    |bsxfun   |2030           |1.50       |
    |meshgrid |3556           |2.43       |
    |repmat   |2411           |2.64       |
    |hankel   |886            |0.43       |
    |for loop |886            |0.82       |