# A very fast way to find elements and their indices? (Is ismember fast?)

8 views (last 30 days)
Sim on 18 Nov 2022
Commented: Sim on 19 Nov 2022
A very fast way to find elements and their indices? (Is ismember fast?)
This would be my example:
% input: create arrays "a" and "b"
a = {'A23'};
l = 'A' : 'Z';
rl = reshape(l,size(l,2),1);
for i = 1 : size(rl,1)
for j = 1 : 10000
f{i,j} = sprintf('%s%d',rl(i), j);
end
end
b = reshape(f,[],1);
% still part of the input: randomly replace 50 values of "b" with {'A23'}
r = round((size(b,1)-1) .* rand(50,1) + 1);
b(r) = a;
% How can I make this part way much faster ?
tic
[~,idx2] = ismember(string(b),string(a));
b_filtered = b(find(idx2),:);
toc
Elapsed time is 0.057298 seconds.
##### 4 CommentsShowHide 3 older comments
Sim on 18 Nov 2022
Edited: Sim on 18 Nov 2022
@Stephen23, yes, I can try the "ismembc" function :-) .....I hope it is "safe", without "side effects" :-)
@John D'Errico, yes, thank you, I have messed up the random part... :-)
@Steven Lord, yes, I will go for "randi", thanks! :-)

Sign in to comment.

### Accepted Answer

Bruno Luong on 18 Nov 2022
Edited: Bruno Luong on 18 Nov 2022
You overly complicate your code for nothing, and yes ismember if fast.
Not sure if your a is always single element or just in this example.
% input: create arrays "a" and "b"
a = {'A23'};
l = 'A' : 'Z';
rl = reshape(l,size(l,2),1);
for i = 1 : size(rl,1)
for j = 1 : 10000
f{i,j} = sprintf('%s%d',rl(i), j);
end
end
b = reshape(f,[],1);
% still part of the input: randomly replace 50 values of "b" with {'A23'}
r = round((size(b,1)-1) .* rand(50,1) + 1);
b(r) = a;
% How can I make this part way much faster ?
tic
[~,idx2] = ismember(string(b),string(a));
b_filtered = b(find(idx2),:);
toc
Elapsed time is 0.062962 seconds.
tic
tf = ismember(b,a);
b_filtered = b(tf,:);
toc
Elapsed time is 0.009279 seconds.
% only when a is scalar
tic
b_filtered = b(strcmp(b, a{1}));
toc
Elapsed time is 0.003851 seconds.
##### 3 CommentsShowHide 2 older comments
Sim on 19 Nov 2022
Thanks a lot @Bruno Luong!! :-)
About: "Not sure if your a is always single element or just in this example.", Yes, it is always a single element (that change in a loop, but always single).

Sign in to comment.

### Categories

Find more on Operators and Elementary Operations in Help Center and File Exchange

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!