I have two cell arrays of strings, and I want to check if they contain the same strings (they do not have to be in the same order, nor do we know if they are of the same len
You can still use ISMEMBER function like you did with a small modification:
arraysAreEqual = all(ismember(a,b)) && all(ismember(b,a))
Also, you can write the loop version with STRCMP as one line:
arraysAreEqual = all( cellfun(@(s)any(strcmp(s,b)), a) )
EDIT: I'm adding a third solution adapted from another SO question:
g = grp2idx([a;b]);
v = all( unique(g(1:numel(a))) == unique(g(numel(a)+1:end)) );
In the same spirit, Im performed the time comparison (using the TIMEIT function):
function perfTests()
a = cellstr( num2str((1:10000)') ); %#' fix SO highlighting
b = a( randperm(length(a)) );
timeit( @() func1(a,b) )
timeit( @() func2(a,b) )
timeit( @() func3(a,b) )
timeit( @() func4(a,b) )
end
function v = func1(a,b)
v = isempty(setxor(a,b)); %# @gnovice answer
end
function v = func2(a,b)
v = all(ismember(a,b)) && all(ismember(b,a));
end
function v = func3(a,b)
v = all( cellfun(@(s)any(strcmp(s,b)), a) );
end
function v = func4(a,b)
g = grp2idx([a;b]);
v = all( unique(g(1:numel(a))) == unique(g(numel(a)+1:end)) );
end
and the results in the same order of functions (lower is better):
ans =
0.032527
ans =
0.055853
ans =
8.6431
ans =
0.022362