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!
댓글 수: 0
채택된 답변
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개)
Andrei Bobrov
2017년 4월 26일
out = accumarray(cumsum([true;diff(b(:))] ~= 0),a(:),[],@(x){unique([x(1),x(end)])})
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!