I have this seq[seq[int]] object:
@[@[2, 4, 1], @[2, 0, 2], @[1, 1, 2], @[0, 0, 0]]
I want to iterate over each column so that I can perform a function on the entire column. So the output should be:
column = @[2, 2, 1, 0]
column = @[4, 0, 1, 0]
column = @[1, 2, 2, 0]
How do I do this?
This works, however I'm looking forward to see what others come up with.
let rows = @[@[2, 4, 1], @[2, 0, 2], @[1, 1, 2], @[0, 0, 0]]
echo("column = ", column)
If you want to work with matrices I advice you to work with a library like Arraymancer instead of doing it by hand.
It will be easier and more efficient.
iterator columns*[T](mat: seq[seq[T]]): seq[T] =
var col = newSeq[T](mat.len)
for c in 0..<mat[0].len:
for r in 0..<mat.len:
col[r] = mat[r][c]
yield col
and then you can do:
let v = @[@[2, 4, 1], @[2, 0, 2], @[1, 1, 2], @[0, 0, 0]]
for i in columns(v):
echo i
@[2, 2, 1, 0]
@[4, 0, 1, 0]
@[1, 2, 2, 0]