GreycLab / gmic

GREYC's Magic for Image Computing: A Full-Featured Open-Source Framework for Image Processing
Other
66 stars 11 forks source link

Feature Request: A function to return the number of unique elements. #13

Closed Reptorian1125 closed 7 months ago

Reptorian1125 commented 1 year ago

Basically, I would like to be able to set const variable with the number of unique elements in a vector. So, const out_size=unique_count([1,2,4,2,2]); and out_size would return 3 because there are only 3 unique elements.

Or better yet, a function to return only unique elements as a vector. Something akin to colormap 0.

dtschump commented 1 year ago

You can write a function that does both things : return the number N of unique elements, and modify the input vector so that the N first values are the unique elements, in increasing order:

foo :
  eval "
    unique_count(X) = (
      ref(X,_uc_X);
      _uc_X = sort(_uc_X);
      _uc_nb_unique = _uc_i = _uc_j = _uc_curr = 0;
      while (_uc_i<size(_uc_X),
        !_uc_i || _uc_X[_uc_i]!=_uc_curr?(++_uc_nb_unique; _uc_X[_uc_j++] = _uc_X[_uc_i]);
        _uc_curr = _uc_X[_uc_i++];
      );
      _uc_nb_unique;
    );

    X = vector10();
    fill(X,int(u(0,10)));
    print(X);

    n = unique_count(X);

    print(X);
    print(n);
  "