How to spread elements in a cell based on vector?
조회 수: 4 (최근 30일)
이전 댓글 표시
Dear all, I have cell b12 with number of elements. R is the first element after the value in vector D1. X is all values after the first element in R, however, X value does not give me the right elements. it only shows the first value after the first value in R? I appreciate if someone help me with this issue.
b12={[3,282,103,271,123,1],[3,282,103,280,260,9],[3,282,55,52,90,12],[3,282,103,280,76,13],[3,282,195,255,23]};%,[3,282,249,143,34],[3,282,103,52,90,41],[3,282,103,280,45],[3,282,103,52],[3,282,195,255,58],[3,282,103,52,63],[3,282,195,73],[3,282,103,280,76],[3,282,249,117,82],[3,282,249,84],[3,282,103,52,90],[3,282,249,143,93],[3,282,108,100],[3,282,103],[3,282,108],[3,282,103,280,110],[3,282,249,117],[3,282,103,271,123],[3,282,103,280,76,125],[3,282,249,143,126],[3,282,108,127],[3,282,128],[3,282,103,52,90,41,134],[3,282,249,143],[3,282,103,280,260,184],[3,282,195],[3,282,103,280,260,197],[3,282,216],[3,282,103,52,217],[3,282,103,280,222],[3,282,103,52,224],[3,282,249,239],[3,282,103,52,90,41,245],[3,282,249],[3,282,103,280,110,254],[3,282,195,255],[3,282,103,280,260],[3,282,103,280,222,262],[3,282,103,271],[3,282,103,280],[3,282],[3,282,103,280,260,296]}
%D1 = many numbers but on here I put only 2 elements.
D1=[282,55];
N = numel(b12);
R = cell(1,N);
X = cell(1,N);
for k = 1:N
idx = ismember(b12{k},D1);
idx = [false,idx(1:end-1)];
if any(idx)
R{k} = b12{k}(find(idx,1,'first'));
end
idx = [false,idx(1:end-1)];
if any(idx)
X{k} = b12{k}(find(idx,1,'first'));
end
end
%Expected results:
R={103,103,55,103,195}
X={271,123,1,280,260,9,52,90,12,280,76,13,195,255,23}
댓글 수: 0
채택된 답변
the cyclist
2018년 8월 6일
For X, I think you want something like
X{k} = b12{k}(find(idx,1,'first')+2:end);
b12={[3,282,103,271,123,1],[3,282,103,280,260,9],[3,282,55,52,90,12],[3,282,103,280,76,13],[3,282,195,255,23]};
D1 = [282,55];
ND1 = numel(D1);
R = cell(1,ND1);
X = cell(1,ND1);
for nd = 1:ND1
R{nd} = cellfun(@(x)x(find(x==D1(nd),1)+1),b12,'Uniform',false);
X{nd} = cell2mat(cellfun(@(x)x(find(x==D1(nd),1)+2:end),b12,'Uniform',false));
end
댓글 수: 4
the cyclist
2018년 8월 6일
Also, it was not clear to me whether you wanted each value of R and X in its own element of the cell array, or all combined into one long vector. Your "expected result" shows them as one long vector, but your code has separate cells.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Entering Commands에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!