Using bsxfun for non-numeric data

조회 수: 5 (최근 30일)
John Doe
John Doe 2013년 6월 13일
댓글: Matt J 2019년 11월 20일
Is there an equivalent to bsxfun for non-numeric data?
For example, I want to compare all pairs of strings stored in two cell-arrays:
a = {'aa', 'bb', 'cc'};
b = {'dd', 'aa'};
bsxfun( @strcmp, a, b' ); % not working for cells
I want something like this:
bsxfun(@eq, 1:3, (1:4)')
ans =
1 0 0
0 1 0
0 0 1
0 0 0

채택된 답변

Matt J
Matt J 2013년 6월 13일
편집: Matt J 2013년 6월 13일
Here's a way you could still do the comparison in the "string domain",
>> ia=(1:length(a)).'; ib=1:length(b);
>> a=a(:);
>> bsxfun(@(i,j) strcmp( a(i),b(j) ) ,ia, ib)
ans =
0 1
0 0
0 0

추가 답변 (2개)

Sean de Wolski
Sean de Wolski 2013년 6월 13일
Yes, bsxfun only supports numeric datatypes.
Here's the workaround I would take: Use unique to convert to numbers and eq as the comparison:
a = {'aa', 'bb', 'cc'};
b = {'dd', 'aa'};
[~,~,idx] = unique([a(:); b(:)],'stable'); %equal numbers instead of strings
ee = bsxfun(@eq,idx(1:numel(a))',idx(numel(a)+1:end));
  댓글 수: 1
David Young
David Young 2019년 11월 20일
It seems like a completely unnecessary restriction for bsxfun to only accept numeric arrays - the function passed as the first argument must surely do its own checking anyway. The trick of using unique is neat, but it's a real shame it's necessary, and it's still not general. You could make bsxfun more powerful simply by taking out the check. All that's needed is that the results can be assembled into an array as arrayfun does.

댓글을 달려면 로그인하십시오.


Steven Lord
Steven Lord 2019년 11월 20일
For this specific example, you can now take advantage of implicit expansion and the string type.
>> a = {'aa', 'bb', 'cc'};
>> b = {'dd', 'aa'};
>> string(a) == string(b).'
ans =
2×3 logical array
0 0 0
1 0 0
  댓글 수: 1
Matt J
Matt J 2019년 11월 20일
Didn't know that implicit expansion applies to non-numeric types! That should get more documentation.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by