containsOctave 中是否有等效于 MATLAB 的函数?或者,是否有比在 Octave 中编写自己的函数来复制此功能更简单的解决方案?我正在从 MATLAB 切换到 Octave,并contains在整个 MATLAB 脚本中使用。
让我们坚持以下文档中的示例contains:在 Octave 中,没有 MATLAB R2017a 中引入的(双引号)字符串。所以,我们需要切换到普通的、旧的(单引号)字符数组。在另请参阅部分中,我们获得了指向 的链接strfind。我们将使用这个函数,它也在 Octave 中实现来创建一个匿名函数,模仿contains. 此外,我们还需要cellfun,它也可以在 Octave 中使用。请查看以下代码片段:
% Example adapted from https://www.mathworks.com/help/matlab/ref/contains.html
% Names; char arrays ("strings") in cell array
str = {'Mary Ann Jones', 'Paul Jay Burns', 'John Paul Smith'}
% Search pattern; char array ("string")
pattern = 'Paul';
% Anonymous function mimicking contains
contains = @(str, pattern) ~cellfun('isempty', strfind(str, pattern));
% contains = @(str, pattern) ~cellfun(@isempty, strfind(str, pattern));
TF = contains(str, pattern)
Run Code Online (Sandbox Code Playgroud)
输出如下:
str =
{
[1,1] = Mary Ann Jones
[1,2] = Paul Jay Burns
[1,3] = John Paul Smith
}
TF =
0 1 1
Run Code Online (Sandbox Code Playgroud)
这应该类似于 MATLAB 的contains.
所以,最后 - 是的,您需要自己复制功能,因为strfind没有确切的替代品。
希望有帮助!
编辑:在调用中使用'isempty'而不是获得更快的内置实现(请参阅下面的carandraug 评论)。@isemptycellfun