Binary search of strings/chars

14 次查看(过去 30 天)
Jacek Szkutnik
Jacek Szkutnik 2020-7-16
回答: Rajanya 2024-11-15,11:58
I have a similar problem to this:
"I would like to perform a binary search of an array of elements in MATLAB, based on some logical condition. The find function, while useful, performs a linear search with runtime complexity O(n).
I would like to know if there is an alternative procedure using the equivalent of a 'binary search' type of method that performs the same in O(log(n)), to determine if an element is contained within an array."
but I would like to search in a cell array containing chars or in string array and the helper functions seem not to work, while ismember function works correctly.
Is there any better way than writing the binary search function for cell arrays myself?

回答(1 个)

Rajanya
Rajanya 2024-11-15,11:58
I understand you are aiming to utilize the time efficiency of binary search on a cell array of characters or strings by using MATLAB's built-in functions, specifically the ‘ismembc’ or ‘ismembc2’ helper functions associated with ‘ismember’.
However, these helper functions are designed to work exclusively with numeric, logical, or character arrays and to my knowledge, ‘ismember’ handles cell arrays of strings differently, which is why they are failing and ‘ismember’ is not in this context.
When dealing only with cell arrays of characters, the cell array can be converted into a character array, allowing the use of ‘ismembc’, as a workaround. For example,
charArray = cell2mat(cellArray)
Unfortunately, I can’t think of a similar workaround for string arrays.
Alternatively, there are toolboxes for binary search online, which I think can be leveraged for your use case, instead of creating a custom function from scratch.
Hope this helps!

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

标签

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by