Dense array -> sparse array


#1

Hi,

I have a dense array with a lot of zeros so I want to convert it into a sparse array with only non-zero elements.

Is there a way that I can do convert an existing dense array to a sparse array?

Thank you in advance!!

MJ


#2

Hi!

How about

filter(array, value <> 0)

That work?


#3

Yes it works!

Thank you so much!

MJ


#4

Hello,
I am wondering here a way to converse a sparse array to a dense array, for example I have a sparse array with the dimension [1,2,3,7,8,10], how can I convert it into a dense array with dimension [1,2,3,4,5,6]?


#5

unpack() does that. Also sort().


#6

A little more detail, to supplement Alex P’s reply.

So let’s start with an example array …

CREATE ARRAY Example 
<
  data1 : double
>
[ index=0:*,10,0 ];

Let’s populate it with some sparse data.

insert ( 
  filter ( 
    build ( 
      < data1 : double > [ index=0:9,10,0 ],
      double(random()%1000)
    ),
    index%2 = 1
  ),
  Example
);

So … Step 1 is to unpack(…), which takes your (sparse) 1D array, and generates a dense 1D array as output. Query looks like this …

unpack ( Example, new_index );

And the result of that query looks like this.

AFL% unpack ( Example, order );
{order} index,data1
{0} 1,985
{1} 3,258
{2} 5,525
{3} 7,815
{4} 9,354

Step 2: re-organize your unpack(…) result into the new shape you want. Query looks like this:

redimension ( 
  unpack ( Example, new_index ), 
  < data1 : double > [ new_index=0:*,10,0 ] 
);

And the result looks like this:

AFL% redimension ( unpack ( Example, new_index ), < data1 : double > [ new_index=0:*,10,0 ] );
{new_index} data1
{0} 985
{1} 258
{2} 525
{3} 815
{4} 354