Find values in array a based on unique values in array b as well as based on the range of values in b
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
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!
0 Commenti
Risposta accettata
Stephen23
il 26 Apr 2017
Modificato: Stephen23
il 26 Apr 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
Più risposte (1)
Andrei Bobrov
il 26 Apr 2017
out = accumarray(cumsum([true;diff(b(:))] ~= 0),a(:),[],@(x){unique([x(1),x(end)])})
0 Commenti
Vedere anche
Categorie
Scopri di più su Matrices and Arrays in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!