如何从在MATLAB阵列中创建等价类 [英] How to create equivalence class from an array in matlab
问题描述
我的工作 MATLAB
并有一个数组:
A =
2 1 5 3 2 1 2 1
您可以看到可能有一个值多次。我想包含数组作为输出的该值的指数(S)一个函数,会给我一个数组为每个价值。
使用上面的例子中,输出将是:
(1 5 7)
(2 6 8)
(3)
(4)
(1 5 7)是2的输入阵列中的索引。同样的情况1,5和3。
这是可以做到用 for循环
等。我只是想知道是否有一些内置的功能,这个 MATLAB
。
结果
**** 修改 ****
有可能两列如下
2 1 5 3 2 1 2 1
3 4 3 2 4 4 3 4
在这种情况下,输出将是
(1 7)
(2 6 8)
(3)
(4)
(5)
使用的 唯一
获得独特的标签 A
,然后应用的 accumarray
用自定义功能
[〜,〜,KK] =唯一的(一','行','稳定'。); %
结果= accumarray(KK,(1:numel(KK))',[],@(X){排序(X)'});
这适用于任何的行数。为了您的两排例如
A = [2 1 5 3 2 1 2 1
3 4 3 2 4 4 3 4];
结果是
结果{1} =
1 7
结果{2} =
2 6 8
结果{3} =
3
结果{4} =
4
结果{5} =
五
如果元素的顺序并不重要,可以简化code一点:
[〜,〜,KK] =唯一的(一','行'。); %
结果= accumarray(KK,(1:numel(KK))',[],@(X){X'});
这使得
结果{1} =
2 6 8
结果{2} =
7 1
结果{3} =
五
结果{4} =
4
结果{5} =
3
I am working on matlab
and have an array:
a =
2 1 5 3 2 1 2 1
You can see there may be one value multiple times. I want a function that will give me an array for each of those value that contains the index(s) of that value in the array as output.
Using the above example, the output would be:
(1 5 7)
(2 6 8)
(3)
(4)
(1 5 7) are the indexes of 2 in the input array. Same happens for 1,5 and 3.
This can be done using for loops
etc. I just want to know if there is some in-built function for this in matlab
.
**** EDIT ****
There may be two columns as following.
2 1 5 3 2 1 2 1
3 4 3 2 4 4 3 4
In that case output will be
(1 7)
(2 6 8)
(3)
(4)
(5)
Use the third output of unique
to get unique labels for each column of a
, and then apply accumarray
with a custom function:
[~, ~, kk] = unique(a.', 'rows', 'stable'); %'
result = accumarray(kk, (1:numel(kk)).', [], @(x) {sort(x).'});
This works for any number of rows. For your two-row example
a = [2 1 5 3 2 1 2 1
3 4 3 2 4 4 3 4];
the result is
result{1} =
1 7
result{2} =
2 6 8
result{3} =
3
result{4} =
4
result{5} =
5
If element order is not important, you can simplify the code a little:
[~, ~, kk] = unique(a.', 'rows'); %'
result = accumarray(kk, (1:numel(kk)).', [], @(x) {x.'});
which gives
result{1} =
2 8 6
result{2} =
7 1
result{3} =
5
result{4} =
4
result{5} =
3
这篇关于如何从在MATLAB阵列中创建等价类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!