slang-users mailing list

[2014 Date Index] [2014 Thread Index] [Other years]
[Thread Prev] [Thread Next]      [Date Prev] [Date Next]

Re: [slang-users] Searching in two dimensional arrays


Morten Bo Johansen <mbj@xxxxxxxxxxx> wrote:
> With one-dimensional arrays one can find a particular value
> with the where () function, fast and elegantly. But how about
> two dimensional arrays? Is there any better/faster way than to
> loop over the array?

There where() function also works with n-d arrays.  In each case, it
returns an array of integers that represent the index offset from the
beginning of the array to the matches:

slsh> .load rand
slsh> x = rand_uniform(5*3); reshape(x, [5,3]);
slsh> x;
Double_Type[5,3]
slsh> print (x);
0.34367452817969024 0.18695593997836113 0.8013190373312682
0.9692114656791091 0.5791763365268707 0.19650518707931042
0.14023283775895834 0.8852414283901453 0.32541245105676353
0.8430562005378306 0.054020636482164264 0.00765162194147706
0.6619170824997127 0.9026132943108678 0.41396057419478893
slsh> i = where (x>0.5);
slsh> print (i);
2
3
4
7
9
12
13
slsh> print (x[i]);
0.8013190373312682
0.9692114656791091
0.5791763365268707
0.8852414283901453
0.8430562005378306
0.6619170824997127
0.9026132943108678

If you want the matching rows and columns, you can use the fact that
the offset i is

    i = col + num_columns * row
==>
    col = i mod num_columns;
    row = i/num_columns;

slsh> num_columns = array_shape (x)[1];   % =3 here
slsh> row = i/num_columns; col = i mod num_columns;
slsh> print (row);
0
1
1
2
3
4
4
slsh> print (col);
2
0
1
1
0
0
1

--John
_______________________________________________
For list information, visit <http://jedsoft.org/slang/mailinglists.html>.


[2014 date index] [2014 thread index]
[Thread Prev] [Thread Next]      [Date Prev] [Date Next]