- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有 n 个元胞数组 c1,c2,... ,cn,尺寸为 L1 × 1,L 2 × 1,…, Ln × 1。 (FWIW,每个元胞数组都包含一个唯一类的元素,但这个类对于所有数组可能都不相同。)
我想生成一个 dataset
对象,表示这些 n 元胞数组的笛卡尔积(也称为“交叉连接”)。
I'm looking for a programmatic way to do this that will work for any n.
要清楚我所说的“笛卡尔积”(或“交叉连接”)的意思:我想生成一个包含 n 列和 L 的数据集对象1 × L2 × … ×Ln 行,c1 中的条目的每个可能组合一行,c2 中的条目, …,来自 cn - 1 的条目,以及来自 cn 的条目。 (可以假设 c1,c2,...,cn 包含重复条目。IOW,可以假设每个 ci 都等于 唯一(
ci)
。)
下面给出了一个 n = 3 的例子;期望的结果是 dataset
对象 factors
。 (当然,factors
的列的名称代表了一个额外的参数。另外,在这个例子中,所有的元胞数组都包含字符串,但是,正如已经提到的,一般来说,不同的数组将包含不同类别的条目。)
>> c1
c1 =
'even'
'odd'
>> c2
c2 =
'green'
'red'
'yellow'
>> c3
c3 =
'clubs'
'diamonds'
'hearts'
'spades'
>> factors
factors =
Parity TrafficLight Suit
'even' 'red' 'spades'
'even' 'red' 'hearts'
'even' 'red' 'diamonds'
'even' 'red' 'clubs'
'even' 'yellow' 'spades'
'even' 'yellow' 'hearts'
'even' 'yellow' 'diamonds'
'even' 'yellow' 'clubs'
'even' 'green' 'spades'
'even' 'green' 'hearts'
'even' 'green' 'diamonds'
'even' 'green' 'clubs'
'odd' 'red' 'spades'
'odd' 'red' 'hearts'
'odd' 'red' 'diamonds'
'odd' 'red' 'clubs'
'odd' 'yellow' 'spades'
'odd' 'yellow' 'hearts'
'odd' 'yellow' 'diamonds'
'odd' 'yellow' 'clubs'
'odd' 'green' 'spades'
'odd' 'green' 'hearts'
'odd' 'green' 'diamonds'
'odd' 'green' 'clubs'
最佳答案
这适用于
它利用了 cellfun
, arrayfun
和 comma-separated lists .使用 ndgrid
在索引(而不是实际元素)上计算笛卡尔积, 与 fliplr
产生您想要的顺序(第一列变化最慢,最后一列变化最快)。
结果以包含 n 列的元胞数组形式给出。如果您需要以数据集的形式使用它,请定义适当的名称并使用 cell2dataset
进行转换。
c1 = {'even','odd'}; %// example data
c2 = {'green','red','yellow'};
c3 = {'clubs','diamonds','hearts','spades'};
sets = {c1, c2, c3}; %// can have an arbirary number of c's
num = numel(sets);
nums = cellfun(@(c) numel(c), sets);
inds = cell(1,num);
vec = fliplr(arrayfun(@(n) 1:n, nums, 'uni', 0));
[inds{:}] = ndgrid(vec{:});
inds = fliplr(inds);
factors = arrayfun(@(n) {sets{n}{inds{n}}},1:num, 'uni', 0);
factors = cat(1, factors{:}).';
结果:
>> factors
factors =
'even' 'green' 'clubs'
'even' 'green' 'diamonds'
'even' 'green' 'hearts'
'even' 'green' 'spades'
'even' 'red' 'clubs'
'even' 'red' 'diamonds'
'even' 'red' 'hearts'
'even' 'red' 'spades'
'even' 'yellow' 'clubs'
'even' 'yellow' 'diamonds'
'even' 'yellow' 'hearts'
'even' 'yellow' 'spades'
'odd' 'green' 'clubs'
'odd' 'green' 'diamonds'
'odd' 'green' 'hearts'
'odd' 'green' 'spades'
'odd' 'red' 'clubs'
'odd' 'red' 'diamonds'
'odd' 'red' 'hearts'
'odd' 'red' 'spades'
'odd' 'yellow' 'clubs'
'odd' 'yellow' 'diamonds'
'odd' 'yellow' 'hearts'
'odd' 'yellow' 'spades'
关于matlab - 如何以编程方式从多个一维元胞数组的笛卡尔积(又名 "cross-join")生成数据集对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21355790/
我是一名优秀的程序员,十分优秀!