Find values in array a based on unique values in array b as well as based on the range of values in b

2 ビュー (過去 30 日間)
Hello Everyone,
I have two long arrays that look like this:
a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
b = [10,14,3,21,21,21,21,3,14,14,14,2,75,13,13,13,100]
I need to construct a cell ( c) that will have values in array a that correspond to unique values in b. However, when b has a value that repeats (e.g. 21 above) then the entry in c should be the smallest value and the largest value in a for that value in b. That is, the result should be as follows:
c = {1,2,3,[4,7],8,[9,11],12,13,[14,16],17}
My code is too complicated and it also does not work in all cases. It looks like this:
[~,uniq_fir] = unique(b,'first');
[~,uniq_las] = unique(b,'last');
uniq_share = intersect(uniq_fir,uniq_las);
uniq_fir_dif = setdiff(uniq_fir,uniq_las);
uniq_las_dif = setdiff(uniq_las,uniq_fir);
uniq1 = a(uniq_share);
uniq2 = sort(a(uniq_fir_dif));
uniq3 = sort(a(uniq_las_dif));
c(uniq_share) = num2cell(uniq1);
empt_cell_temp = find(cellfun(@isempty,c));
for i = 1:length(uniq_fir_dif)
c{empt_cell_temp(i)} = [uniq2(i),uniq3(i)];
end
Please can anybody help me with this problem? Much obliged!

採用された回答

Stephen23
Stephen23 2017 年 4 月 26 日
編集済み: Stephen23 2017 年 4 月 26 日
A = [ 1, 2, 3, 4, 5, 6, 7,8, 9,10,11,12,13,14,15,16, 17];
B = [10,14, 3,21,21,21,21,3,14,14,14, 2,75,13,13,13,100];
X = find([true,diff(B)~=0,true]);
fun = @(b,e)A(unique([b,e]));
out = arrayfun(fun,X(1:end-1),X(2:end)-1,'uni',0);
and the output:
>> out{:}
ans = 1
ans = 2
ans = 3
ans =
4 7
ans = 8
ans =
9 11
ans = 12
ans = 13
ans =
14 16
ans = 17
  1 件のコメント
djr
djr 2017 年 4 月 26 日
Thank you so much. So elegant and works perfectly. You saw my messy code that did not work by the way :) Thanks!

サインインしてコメントする。

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2017 年 4 月 26 日
out = accumarray(cumsum([true;diff(b(:))] ~= 0),a(:),[],@(x){unique([x(1),x(end)])})

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by