Search through every vector in cell array for the vector that contains a certain value
1 次查看(过去 30 天)
显示 更早的评论
Hiya,
I have the below code, which instead of searching through every vector in the cell array for a vector that contains the number 1, it goes to the last vector in the cell array and returns false.
my cell array is called nodey and contains in position {1,1} - [1,2] and in position {1,2} - [3,4]
for i = 1:length(nodey)
ismember(nodey{i},1);
end
I need it so that it returns true for the first vector, and then i can return nodey{i} and it'll be [1,2] since the value is in the first vector
Thanks!
0 个评论
采纳的回答
per isakson
2020-4-12
Try this
%%
nodey = {[1,2],[3,4]};
%%
has_one = false(1,length(nodey));
for ii = 1:length(nodey)
has_one(ii) = ismember( 1, nodey{ii} );
end
%%
has_one
nodey{ has_one }
%%
ix_one = find( has_one )
nodey{ ix_one }
it displays
has_one =
1×2 logical array
1 0
ans =
1 2
ix_one =
1
ans =
1 2
更多回答(1 个)
dpb
2020-4-12
Your code above doesn't save the result going thru the loop so you only show the final result at the end---
ix=cellfun(@(v) ismember(1,v),nodey,'UniformOutput',1);
>> ix
ix =
2×1 logical array
1
0
>>
Better form for coding would be to put the value to search for in a variable so can only change the variable to look for alternate values...
VFIND=1;
ix=cellfun(@(v) ismember(VFIND,v),nodey,'UniformOutput',1);
BTW: NB the order of arguments to ismember to have the first value the one-element searched-for value so returns a single result instead of a logical vector of numel(nodey) as the first output.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!