MATLAB:return 在 SPLITAPPLY 中使用时来自 ISMEMBER 的两个参数

MATLAB: return both arguments from ISMEMBER when used inside SPLITAPPLY

splitapply 中使用时,如何访问 ismember 的两个参数?

slitapply 每个组只有 returns 标量值,所以为了计算每个组的非标量值(由 return 的第一个参数编辑 ismemebr),必须将匿名函数(在本例中为 ismember)括在大括号 {} 到 return 元胞数组中。

但是现在,当我向 splitapply 提供两个输出参数时,出现错误:

Output argument "varargout{2}" (and maybe others) not assigned during call to "@(x,y) {ismember(x,y)}"

添加 1

我可以创建另一个函数,例如 ismember2cell,它将应用 ismember 并将输出转换为元胞数组:

function [a, b] = ismember2cell(x,y)
  [a,b] = ismember(x,y);
  a = {a};
  b = {b};
end

但也许有一个不需要此解决方法的解决方案。

我找不到全局解决方案,但是 the accepted answer of this post 帮助我为您的问题定义了一个辅助函数:

function varargout = out2cell(varargin)
[x{1:nargout}]=feval(varargin{:});
varargout = num2cell(x);

我觉得你可以调用成功

splitapply(@(x,y) out2cell(@ismember, x, y), A, B);

一个可能更快的选择是只做 splitapply is already doing under the hood by splitting your data into cell arrays (using functions like mat2cell or accumarray) and then using cellfun to apply your function across them. Using cellfun will allow you to easily capture multiple outputs (such as from ismember)。例如:

% Sample data:
A = [1 2 3 4 5];
B = [1 2 1 5 5];
G = [1 1 1 2 2];  % Group index

% Group data into cell arrays:
cellA = accumarray(G(:), A(:), [], @(x) {x(:).'});  % See note below about (:).' syntax
cellB = accumarray(G(:), B(:), [], @(x) {x(:).'});

% Apply function:
[Lia, Locb] = cellfun(@ismember, cellA, cellB, 'UniformOutput', false);

注意: 我的示例数据是行向量,但我不得不使用 colon operator to reshape them into column vectors when passing them to accumarray (it wants columns). Once distributed into a cell array, each piece of the vector would still be a column vector, and I simply wanted to keep them as row vectors to match the original sample data. The syntax (:).' is a colon reshaping followed by a nonconjugate transpose,无论 [= 的形状如何,都确保了行向量的结果19=]。在这种情况下,我可能只使用 .',但我养成了从不假设变量形状的习惯。