MATLAB: How to shift and repeat an element within a matrix

loopmatrixrow shifting

Hi all, Please, what's a neat way to build a matrix like this:
0 0 1 0 0 0;
0 1 0 0 0 0;
1 0 0 0 0 0;
0 1 0 0 0 0;
0 0 1 0 0 0;
0 0 0 1 0 0;
I want to make a larger matrix with a similar pattern, where the 1's change direction once they hit the left column.
Thanks! Mike.

Best Answer

idx = 3;
n = 6;
res = zeros(n);
turnIdx = n * ( idx - 1 ) + 1; % 1 element after the end of the idx-1 row
res( idx:(n-1):turnIdx ) = 1;
res( turnIdx:(n+1):end ) = 1;
res = res.';
should do the job if your problem is not actually more complex than what you describe (e.g. arrays taller than wide where you expect it to turn again on hitting the right edge.
idx is the index of the 1 on the first row, n is the size of one dimension of the square matrix.