index of an array multiple same element
3 次查看(过去 30 天)
显示 更早的评论
How can find the index of an array element if it have element have the same value for example a=[7 8 8 2 5 6 6 2 6 8] what is the index of third 8 and 6. I used find(A==8,1, firs) this gave the first one only, and how can I know the element have more than one value.
回答(3 个)
Stephen23
2019-2-26
>> a = [7,8,8,2,5,6,6,2,6,8];
>> U = unique(a) % the order is the same as C.
U =
2 5 6 7 8
>> [R,C] = find(U(:)==a);
>> C = accumarray(R,C,[],@(v){v});
>> C{:} % same order as U.
ans =
4
8
ans =
5
ans =
6
7
9
ans =
1
ans =
2
3
10
0 个评论
Andrei Bobrov
2019-2-25
编辑:Andrei Bobrov
2019-2-26
[a1,~,ii] = unique(a,'stable');
out = [num2cell(a1(:)),accumarray(ii,(1:numel(ii))',[],@(x){sort(x)})];
2 个评论
Andrei Bobrov
2019-2-26
I'm fixed my typo in answer:
[a1,~,ii] = unique(a,'stable');
out = [num2cell(a1(:)),accumarray(ii,(1:numel(ii))',[],@(x){sort(x)})];
madhan ravi
2019-2-25
编辑:madhan ravi
2019-2-25
u=unique(a);
C=arrayfun(@(x) find(a==u(x)),1:numel(u),'un',0);
%celldisp(C)
1 个评论
madhan ravi
2019-2-25
If you want the order to be preserved then use 'stable' as an option in unique.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!