How to create a symmetrical matrix out of a column?

For example, I want to turn the following column:

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

into the matrix:

[ 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] 

What algorithm would I use?

So far I have:

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

Upvotes: 0

Views: 90

Answers (3)

rahnema1
rahnema1

Reputation: 15867

The hankel function can be used to generate the matrix:

col = [90; 175; 600; 650; 655; 660] 
result = hankel(col, flip(col));

Upvotes: 3

Luis Mendo
Luis Mendo

Reputation: 112759

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

Upvotes: 3

Jamie S
Jamie S

Reputation: 111

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.

Upvotes: 2

Related Questions