RosettaCodeData/Task/Zig-zag-matrix/Octave/zig-zag-matrix-3.octave
2020-02-17 23:21:07 -08:00

57 lines
1.3 KiB
Text

#{
Produce a zigzag matrix. Nigel Galloway, January 26th., 2020.
At the time of writing the Rascal solution is yellow flagged for producing a striped matrix.
Let me make the same faux pas.
#}
n=5; g=1;
for e=1:n i=1; for l=e:-1:1 zig(i++,l)=g++; endfor endfor
for e=2:n i=e; for l=n:-1:e zig(i++,l)=g++; endfor endfor
#{
I then have the following, let me call it zig.
1 2 4 7 11
3 5 8 12 16
6 9 13 17 20
10 14 18 21 23
15 19 22 24 25
To avoid being yellow flagged I must convert this striped matrix into a zigzag matrix.
#}
zag=zig'
#{
So zag is the transpose of zig.
1 3 6 10 15
2 5 9 14 19
4 8 13 18 22
7 12 17 21 24
11 16 20 23 25
#}
for e=1:n for g=1:n if(mod(e+g,2))==0 zagM(e,g)=1; endif endfor endfor; zigM=1-zagM;
#{
I now have 2 masks:
zigM =
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
zagM =
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
#}
zigzag=zag.*zagM+zig.*zigM;
#{
zigzag =
1 2 6 7 15
3 5 8 14 16
4 9 13 17 22
10 12 18 21 23
11 19 20 24 25
#}