Search through every vector in cell array for the vector that contains a certain value
1 view (last 30 days)
Show older comments
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 Comments
Accepted Answer
per isakson
on 12 Apr 2020
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
More Answers (1)
dpb
on 12 Apr 2020
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.
See Also
Categories
Find more on Logical 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!