I have some multi-dimensional array (not a vector) how to setf its
elements one by one?
For example setting 2 dimensional culd be done with below, but what if
number of axis is not know until runtime?
1 >(setq arr (make-array '(2 3)))
#2A((NIL NIL NIL) (NIL NIL NIL))
2 > (dotimes (I1 2)
(dotimes (i2 3)
(setf (aref arr i1 i2) (random 10))))
NIL
3 > arr
#2A((8 5 4) (4 3 8))
From: John Thingstad
Subject: Re: How to loop over multi-dimesional array
Date:
Message-ID: <op.uut785kvut4oq5@pandora>
På Mon, 01 Jun 2009 10:09:24 +0200, skrev Slobodan Blazeski
<·················@gmail.com>:
> I have some multi-dimensional array (not a vector) how to setf its
> elements one by one?
> For example setting 2 dimensional culd be done with below, but what if
> number of axis is not know until runtime?
>
> 1 >(setq arr (make-array '(2 3)))
> #2A((NIL NIL NIL) (NIL NIL NIL))
>
> 2 > (dotimes (I1 2)
> (dotimes (i2 3)
> (setf (aref arr i1 i2) (random 10))))
> NIL
>
> 3 > arr
> #2A((8 5 4) (4 3 8))
look up row-major-aref and array-total-size
(dotimes (i (array-total-size array))
(setf (row-major-aref array i) (random 10)))
Otherwise array-dimensions gives the dimensions as a list so:
(loop for j = 0 then (incf j)
for size in (array-dimensions array)
do (dotimes (i size) (setf (aref array j i) (random 10)))
or something like that.
---------------------
John Thingstad
On Jun 1, 10:52 am, "John Thingstad" <·······@online.no> wrote:
> På Mon, 01 Jun 2009 10:09:24 +0200, skrev Slobodan Blazeski
> <·················@gmail.com>:
>
> > I have some multi-dimensional array (not a vector) how to setf its
> > elements one by one?
> > For example setting 2 dimensional culd be done with below, but what if
> > number of axis is not know until runtime?
>
> > 1 >(setq arr (make-array '(2 3)))
> > #2A((NIL NIL NIL) (NIL NIL NIL))
>
> > 2 > (dotimes (I1 2)
> > (dotimes (i2 3)
> > (setf (aref arr i1 i2) (random 10))))
> > NIL
>
> > 3 > arr
> > #2A((8 5 4) (4 3 8))
>
> look up row-major-aref
Row-major-aref is just what I needed many thanks.
cheers
bobi
>and array-total-size
>
> (dotimes (i (array-total-size array))
> (setf (row-major-aref array i) (random 10)))
>
> Otherwise array-dimensions gives the dimensions as a list so:
>
> (loop for j = 0 then (incf j)
> for size in (array-dimensions array)
> do (dotimes (i size) (setf (aref array j i) (random 10)))
>
> or something like that.
>
> ---------------------
> John Thingstad