I have been doing Gilbert Strang’s linear algebra assignments, some of which require you to write short scripts in MatLab, though I use GNU Octave (which is kind of like a free MatLab). I was trying out this problem:

To solve this quickly, it would have been nice to have a function that would give a list of permutation matrices for every **n-sized **square matrix, but there was none in Octave, so I wrote a function *permMatrices* which creates a list of permutation matrices for a square matrix of size **n**.

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters

% function to generate permutation matrices given the size of the desired permutation matrices | |

function x = permMatrices(n) | |

x = zeros(n,n,factorial(n)); | |

permutations = perms(1:n); | |

for i = 1:size(x,3) | |

x(:,:,i) = eye(n)(permutations(i,:),:); | |

end | |

endfunction |

**For example:**

**The MatLab / Octave code to solve this problem is shown below:**

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters

% Solution for part (a) | |

p = permMatrices(3); | |

n = size(p,3); % number of permutation matrices | |

v = zeros(n,1); % vector of zeros with dimension equalling number of permutation matrices | |

% check for permutation matrices other than identity matrix with 3rd power equalling identity matrix | |

for i = 1:n | |

if p(:,:,i)^3 == eye(3) | |

v(i,1) = 1; | |

end | |

end | |

v(1,1) = 0; % exclude identity matrix | |

ans1 = p(:,:,v == 1) | |

% Solution for part (b) | |

P = permMatrices(4); | |

m = size(P,3); % number of permutation matrices | |

t = zeros(m,1); % vector of zeros with dimension equalling number of permutation matrices | |

% check for permutation matrices with 4th power equalling identity matrix | |

for i = 1:m | |

if P(:,:,i)^4 == eye(4) | |

t(i,1) = 1; | |

end | |

end | |

% print the permutation matrices | |

ans2 = P(:,:,t == 0) |

**Output:**