On 04/08/2023 20:24, Josué Martínez-Castillo wrote:
> Thank you both, Artur and sven. Both approaches were very helpful. I
> finally used:
>
>> _ _
>> # mymatrix: column1 = income, column2 = frequency
>> matrix mymatrix = {35, 5; 120, 5; 150, 0; 320, 6; 400, 5}
>> matrix result = {}
>> loop i=1..5
>> result |= mshape(mymatrix[i,1], mymatrix[i,2], 1)
>> endloop
>> print mymatrix result
>> _ _
The best generalisation I could find to the 2-way (xtab) case is as follows:
<hansl>
set seed 1234567
nr = 3
nc = 2
### xtab case
xt = mrandgen(i, 0, 6, nr, nc)
tot = nr * nc
result = zeros(sum(xt), 2)
fin = 0
loop j = 1 .. nc
loop i = 1 .. nr
x = xt[i,j]
if x > 0
ini = fin+1
fin += x
result[ini:fin,] = mshape({i,j}, 2, x)'
endif
endloop
endloop
print xt result
</hansl>
On the other hand, Sven's remark made me think that sometimes you might
want to compute all possible indices of a arbitrarily-sized tensor. Once
you have those, you can use them in a single loop without having to nest
many.
The function is:
<hansl>
function matrix indices(matrix dims)
n = nelem(dims)
if n == 0
ret = {}
elif n == 1
ret = seq(1, dims[1])'
else
matrix a = indices(dims[-1])
scalar d = dims[1]
scalar m = rows(a)
b = vec(mshape(seq(1,d), d, m)')
a = ones(d,1) ** a
ret = b ~ a
endif
return ret
end function
</hansl>
So for example, you can create X = indices({2,3}), which would yield
1 1
1 2
1 3
2 1
2 2
2 3
and loop over the rows of X instead of a nested loop construct such as
<hansl>
loop i = 1 .. 2
loop j = 1 .. 3
# do things
endloop
endloop
</hansl>
The nice thing is, the number of elements in the argument to the
"indices" function is potentially unlimited. For example,
indices({3,2,3}) returns
1 1 1
1 1 2
1 1 3
1 2 1
1 2 2
1 2 3
2 1 1
2 1 2
2 1 3
2 2 1
2 2 2
2 2 3
3 1 1
3 1 2
3 1 3
3 2 1
3 2 2
3 2 3
Maybe we could add this to the extra addon?
-------------------------------------------------------
Riccardo (Jack) Lucchetti
Dipartimento di Scienze Economiche e Sociali (DiSES)
Università Politecnica delle Marche
(formerly known as Università di Ancona)
r.lucchetti@univpm.it
http://www2.econ.univpm.it/servizi/hpp/lucchetti
-------------------------------------------------------
_______________________________________________
Gretl-users mailing list -- gretl-users@gretlml.univpm.it
To unsubscribe send an email to gretl-users-leave@gretlml.univpm.it
Website: https://gretlml.univpm.it/postorius/lists/gretl-users.gretlml.univpm.it/