Clear Filters
Clear Filters

take part of cell depend on vector

2 views (last 30 days)
Dear all, I have cell (a) and vector (b), I wanna check each number in b that repeat it in a and take each cell from (a) make it as vector by loop.
a=[{[1,9,79,3] [2,29,16,7,3] 3 [4,74,3] [5,73,79,3] [6,56,3] [7,3]}] ;
b=[ 79 3 74 10];
results should be as follow:
cell-part 79= [1,9,79,3,5,73,79,3]
cell_part 3 = [1,9,79,3,2,29,16,7,3,3,4,74,3,5,73,79,3,6,56,3,7,3];
cell_part 74 = [4,74,3]
cell_part 10 = {0};

Accepted Answer

Stephen23
Stephen23 on 31 Dec 2016
Edited: Stephen23 on 31 Dec 2016
As you were already told in your last question, this is not a good idea: naming variables dynamically will make your code slow, buggy, and hard to follow. Read this to know why:
A much better solution is to learn to use indexing, which is fast and efficient:
>> a = {[1,9,79,3],[2,29,16,7,3],3,[4,74,3],[5,73,79,3],[6,56,3],[7,3]};
>> b = [79,3,74,10];
>> idc = cellfun(@(x)any(bsxfun(@eq,x,b(:)),2),a,'Uni',0);
>> out = cellfun(@(x)[a{x}],num2cell([idc{:}],2),'Uni',0);
which gives exactly the output vectors that you specified, inside the cell array out:
>> out{1}
ans =
1 9 79 3 5 73 79 3
>> out{2}
ans =
Columns 1 through 15
1 9 79 3 2 29 16 7 3 3 4 74 3 5 73
Columns 16 through 22
79 3 6 56 3 7 3
>> out{3}
ans =
4 74 3
>> out{4}
ans =
[]

More Answers (0)

Categories

Find more on Matrices and Arrays 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!