Effacer les filtres
Effacer les filtres

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

1 vue (au cours des 30 derniers jours)
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!

Réponse acceptée

Stephen23
Stephen23 le 26 Avr 2017
Modifié(e) : Stephen23 le 26 Avr 2017
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 commentaire
djr
djr le 26 Avr 2017
Thank you so much. So elegant and works perfectly. You saw my messy code that did not work by the way :) Thanks!

Connectez-vous pour commenter.

Plus de réponses (1)

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

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by