How to spread elements in a cell based on vector?

3 views (last 30 days)
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}

Accepted Answer

the cyclist
the cyclist on 6 Aug 2018
For X, I think you want something like
X{k} = b12{k}(find(idx,1,'first')+2:end);
The following code vectorizes the whole thing using the cellfun function.
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 Comments
the cyclist
the cyclist on 6 Aug 2018
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.
laith Farhan
laith Farhan on 6 Aug 2018
Dear Cyclist,
This code "X{k} = b12{k}(find(idx,1,'first'):end)", totally works. I really appreciate it .
Many thanks

Sign in to comment.

More Answers (0)

Categories

Find more on Entering Commands in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!