How to create a symmetrical matrix out of a column?

后端 未结 3 1288
南笙
南笙 2021-01-28 16:19

For example, I want to turn the following column:

[90; 175; 600; 650; 655; 660] 

into the matrix:

[ 90, 175, 600, 650, 655, 66         


        
相关标签:
3条回答
  • 2021-01-28 16:41

    The built-in function toeplitz gives what you want after a couple of flips:

    >> col = [90; 175; 600; 650; 655; 660];
    >> result = flipud(toeplitz(flip(col)))
    result =
        90   175   600   650   655   660
       175   600   650   655   660   655
       600   650   655   660   655   650
       650   655   660   655   650   600
       655   660   655   650   600   175
       660   655   650   600   175    90
    
    0 讨论(0)
  • 2021-01-28 16:41

    The following code will do what you want:

    col = [90; 175; 600; 650; 655; 660];
    numrows = size(col, 1);
    Z = zeros(numrows, numrows);
    for i = 1:numrows
        for j = 1:numrows
            Z(i,j) = col(numrows - abs(numrows - (i+j-1)) );
        end
    end
    

    One critical flaw with your understanding of the code is shown by the line Z(j,i) = col(i) immediately following Z(i,j) = col(i). Given that you're looping through every index of the matrix, this will cause many indexes to be written to more than once, with different result each time. It does give you a symmetrical pattern, but not what you want. Instead of using Z(i,j) and Z(j,i), you should (as I have, above) only assign to Z(i,j) once, and instead calculate the index of col to use from both i and j.

    0 讨论(0)
  • 2021-01-28 16:49

    The hankel function can be used to generate the matrix:

    col = [90; 175; 600; 650; 655; 660] 
    result = hankel(col, flip(col));
    
    0 讨论(0)
提交回复
热议问题