使用`bsxfun`处理非数值数据 [英] Using `bsxfun` for non-numeric data

查看:74
本文介绍了使用`bsxfun`处理非数值数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

非数值数据是否等于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 :-(

据我所知,您可以:

  1. 遵循Oleg的建议并使用循环
  2. 使用现有的实施方式,例如 mAryCellFcn csxfun
  3. 滚动您自己的功能.例如,这是罗伯特(Robert)思想的一种变体,可用于任何尺寸的输入(当然,在bsxfun的限制下)和任意二进制函数func:

  1. Follow Oleg's suggestion and use loops
  2. Use existing implementations such as mAryCellFcn or csxfun from the File Exchange.
  3. 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 function func:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆