How to create a symmetrical matrix out of a column?

后端 未结 3 1292
南笙
南笙 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 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.

提交回复
热议问题