find array inside a cell
3 次查看(过去 30 天)
显示 更早的评论
I have a A={[1,2,4],[2,3,7],[2,5],[4,5,6]} and B=[1;2;3;6;8]
I want to write a code that find B inside A.
the result should be c={[1,2],[2,3],[2],[6]}.
I try this code
c=cell(1, size(A,2));
for i=1:size(A,2)
current=A{i};
for j=1:size(B,1)
index_X = find(A{i} == B(j));
if isempty(index_X)==0
c{i}(end+1)=B(index_X);
end
end
end
but it does not work
0 个评论
采纳的回答
Stephen23
2019-1-15
编辑:Stephen23
2019-1-15
Simpler in one line:
>> A = {[1,2,4],[2,3,7],[2,5],[4,5,6]};
>> B = [1;2;3;6;8];
>> C = cellfun(@(m)intersect(m,B),A,'uni',0);
>> celldisp(C)
C{1} =
1
2
C{2} =
2
3
C{3} =
2
C{4} =
6
14 个评论
Stephen23
2019-1-22
编辑:Stephen23
2019-1-22
Now you seem to indicate that it should be [2,3,5,7] for the first cell. Which is correct?
Perhaps this does what you want:
>> A = {[1,2,4],[2,3,7],[2,5],[4,5,6]};
>> B = [1,2;1,5;2,3;2,4;2,5;3,4;4,7];
>> F = @(v)find(any(v==B(:,1),2)&~any(v==B(:,2),2));
>> C = cellfun(F,A,'uni',0)
>> C{:}
ans =
2
3
5
7
ans =
4
5
6
ans =
3
4
ans =
7
更多回答(1 个)
madhan ravi
2019-1-15
编辑:madhan ravi
2019-1-15
A={[1,2,4],[2,3,7],[2,5],[4,5,6]} ;
B=[1;2;3;6;8];
Result=cell(1,numel(A)); % preallocate
for i = 1:numel(A)
idx=ismember(A{i},B);
Result{i}=A{i}(idx);
end
celldisp(Result)
Gives:
Result{1} =
1 2
Result{2} =
2 3
Result{3} =
2
Result{4} =
6
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Standard File Formats 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!