take part of cell depend on vector
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
skysky2000
am 31 Dez. 2016
Kommentiert: skysky2000
am 2 Jan. 2017
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};
1 Kommentar
Akzeptierte Antwort
Stephen23
am 31 Dez. 2016
Bearbeitet: Stephen23
am 31 Dez. 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 =
[]
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!