使用`bsxfun`处理非数值数据 [英] Using `bsxfun` for non-numeric data
问题描述
非数值数据是否等于bsxfun
?
例如,我想比较存储在两个单元格数组中的所有字符串对:
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'm afraid there's no such equivalent for cell-arrays :-(
据我所知,您可以:
- 遵循Oleg的建议并使用循环
- 使用现有的实施方式,例如
mAryCellFcn
或csxfun
-
滚动您自己的功能.例如,这是罗伯特(Robert)思想的一种变体,可用于任何尺寸的输入(当然,在
bsxfun
的限制下)和任意二进制函数func
:
- Follow Oleg's suggestion and use loops
- Use existing implementations such as
mAryCellFcn
orfrom the File Exchange.csxfun
Roll your own function. For example, here's a variant of Robert's idea that works for inputs of any dimensions (under the restrictions of
bsxfun
, of course) and an arbitrary binary functionfunc
:
function C = mybsxfun(func, A, B)
idx_A = reshape(1:numel(A), size(A));
idx_B = reshape(1:numel(B), size(B));
C = bsxfun(@(ii, jj)func(A(ii), B(jj)), idx_A, idx_B);
如果您的函数可以对整个单元数组进行逐个元素运算,则可以先对单元数组执行单例扩展,然后将其直接馈送到函数func
:
If your function can operate on entire cell arrays element-wise, you could perform a singleton expansion on your cell arrays first, and then feed them directly to the function func
:
mask = bsxfun(@or, true(size(A)), true(size(B)));
idx_A = bsxfun(@times, mask, reshape(1:numel(A), size(A)));
idx_B = bsxfun(@times, mask, reshape(1:numel(B), size(B)));
C = func(A(idx_A), B(idx_B));
如果func
针对单元阵列上的矢量化操作进行了优化,则后一种方法可能会更快.
The latter method might be faster if func
is optimized for vectorized operations on cell arrays.
这篇关于使用`bsxfun`处理非数值数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!