[scilab-Users] Emulate Matlab's ismember function in Scilab
Samuel Gougeon
Samuel.Gougeon at univ-lemans.fr
Tue Nov 10 23:27:48 CET 2009
Hi,
----- Message d'origine -----
De : Sébastien Bihorel
Date : 08/11/2009 12:29:
> Dear Scilab users,
>
> Is there an easy method to emulate the Matlab ismember function to
> match numerical vectors to one another? I've tried several things
> with intersect but it does not seem to give consistent results.
>
> Here is a section of the Matlab help about ismember:
> [tf, loc] = ismember(A, S, ...) returns an array loc containing the
> *highest *index in S for each element in A that is a member of S.
>
>
> Here is an example of Scilab code that I tried
> a = [5 3 1 7 2 9 2 6 4 1 3 6 8 0 1 4];
> b=1:5;
> [v,ka,kb]=intersect(a,b,'c');
>
> Surprisingly, ka is a mix of low, middle or high indexes... There must
> a logic behind that, but I do not see the pattern.
>
>
> I am looking to extract only the highest indexes. Any help would be
> appreciated.
>
> Sebastien
Here is a function that works like Matlab for giving loc :
-----------
function loc = ismember(A,S, highest)
// loc = ismember(A, S, highest)
//
// A : Matrix of booleans, integers, reals, complexes, polynomes
// S : Matrix of same datatype than S
// highest : Scalar boolean
//
// ismember() returns a matrix loc of A's format. loc(i,j) = linear
// index in S of the first (highest ==%F) | last (highest==%T)
// occurrence of A(i,j). Zero is returned in A(i,j) if no occurrence
is found
//
LA=length(A);
LS=length(S);
A2=matrix(A,LA,1)*ones(1,LS) ;
S2=(matrix(S,LS,1)*ones(1,LA)).' ;
d01 =double(A2==S2);
S_ind=ones(LA,1)*(1:LS);
tmp=d01.*S_ind;
if highest,
tmp2=max(tmp,'c');
else
tmp(tmp==0)=%inf; // removes zeros as min values
tmp2=min(tmp,'c');
tmp2(tmp2==%inf)=0;
end
loc=matrix(tmp2,size(A));
endfunction
--------
ismember() works with any datatype, as long as elements
can be multiplied by reals and compared each other with "==".
A test with reals gives:
-->A,S
A =
7. 3.
2. 0.
8. 1.
S =
5. 8. 0. 4.
3. 4. 7. 7.
3. 6. 6. 2.
7. 5. 5. 8.
-->ismember(A,S,%f)
ans =
4. 2.
15. 9.
5. 0.
-->ismember(A,S,%t)
ans =
14. 3.
15. 9.
16. 0.
HTH,
Regards
Samuel
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.scilab.org/pipermail/users/attachments/20091110/f0b3bd49/attachment.htm>
More information about the users
mailing list