2

I'd like to use an example to show what I want.

A = [5 1 2 4 3]; % of distinct values

B = [3 3 1 5 2];

Can I find a library function implemented in MATLAB such that:

C = [5 5 2 3 1] = someFun(A, B)

i.e. C(i) = find(A == B(i))

Note that I am asking for a library function, as in that case it is highly optimized. If you are sure there doesn't exist such a function, that is also an answer.

0

3 Answers 3

3

I would do:

IX(A) = [1:length(A)];
C=IX(B)

This is 10 times faster than the ismember solution:

A=randperm(1e5);
B=ceil(rand(1,1e4)*length(A));

tic; 
[D,C1]=ismember(B,A); 
toc % Elapsed time is 0.013728 seconds.


tic
IX(A) = [1:length(A)];
C=IX(B);
toc % Elapsed time is 0.001506 seconds.

But this can be used under stricter conditions:

  1. A contains only unique integers.
  2. 0 < B(i) < max(A) for all i
  3. The memory can hold an array of size max(A)
Sign up to request clarification or add additional context in comments.

1 Comment

A very nice answer. +1 for you.
1

A couple of solutions:

for-loop

C = zeros(size(B));
for i=1:numel(B)
    C(i) = find(A == B(i));
end

arrayfun

C = arrayfun(@(n)find(A==n), B)

vectorized equality using BSXFUN

[C,~] = find( bsxfun(@eq, B, A.') )

ismember

[~,C] = ismember(B,A)

3 Comments

personally I would go with ISMEMBER
+1 but watch out that '. It won't work if A is complex. It should be .'
right, we don't want the complex conjugates.. I'd also be careful if the number are floating-points not just integers, and instead check that the absolute difference is less than some epsilon threshold
0

Can you clarify your question a little bit?

If you want a function that returns the index of A that contains the value B(i) then a function like this should work:

for(int i = 0; i < B.length; i++)
{
    for(int q = 0; q < A.length; q++)
    {
        if(B[i] == A[q])
           C[i] = q;
    }
}

1 Comment

Thanks. Plz see my revised question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.