Search entire multi level cell array for matching string
26 ビュー (過去 30 日間)
古いコメントを表示
I am trying to search a cell of cell arrays for a matching string without using a for loop due to the inefficiency and speed. My first idea was to use an anonymous function and strip out the top layer iteratively of the cell array in the form of
cellfun(@(cell) cell{1}, MyCellofCellArray, 'UniformOutput', false);
However, let's say for example I have an uneven cell of cell array where
MyCellArray{1} = 1x1 cell,
MyCellArray{2} = 1x2 cell,
MyCellArray{3} = 1x3 cell.
If you try to use the aforementioned cellfun, you get an error "Index exceeds matrix dimensions" because MyCellArray{1} only contains a 1x1 cell. Anyone have any ideas or suggestions?
Thanks,
JWelch
3 件のコメント
採用された回答
James Tursa
2015 年 8 月 6 日
編集済み: James Tursa
2015 年 8 月 6 日
Does this do what you want?
mystring = whatever string you are trying to find
MyCellArrays = [cellfun(@(x)x(:)',MyCellArray,'UniformOutput',false)];
NewCellArrays = [MyCellArrays{:}];
x = find(~cellfun(@isempty,strfind(NewCellArrays,mystring)));
n = cellfun(@numel,MyCellArray);
nsum = cumsum(n);
first = find(nsum>=x,1);
if( first == 1 )
second = x;
else
second = x - nsum(first-1);
end
The element is then MyCellArray{first}{second}
If the string is not guaranteed to be present, then test for x being empty before executing the remaining code.
その他の回答 (1 件)
Cedric
2015 年 8 月 6 日
編集済み: Cedric
2015 年 8 月 6 日
If you have 2015a or above, this can be an occasion for playing with the new REPELEM function:
linId = strcmpi( [MyCellArray{:}], 'str32' ) ;
lookup = repelem( 1:numel(MyCellArray), cellfun( @numel, MyCellArray )) ;
id = [lookup(linId), sum( lookup(1:find(linId) == lookup(linId)) )] ;
This produces
id =
3 2
2 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!