Is there an equivalent of MATLAB's contains
function in Octave? Or, is there a simpler solution than writing my own function in Octave to replicate this functionality? I am in the process of switching to Octave from MATLAB and I use contains
throughout my MATLAB scripts.
Let's stick to the example from the documentation on contains
: In Octave, there are no (double-quoted) strings as introduced in MATLAB R2017a. So, we need to switch to plain, old (single-quoted) char arrays. In the see also section, we get a link to strfind
. We'll use this function, which is also implemented in Octave to create an anonymous function mimicking the behaviour of contains
. Also, we will need cellfun
, which is available in Octave, too. Please see the following code snippet:
% 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)
The output is as follows:
str =
{
[1,1] = Mary Ann Jones
[1,2] = Paul Jay Burns
[1,3] = John Paul Smith
}
TF =
0 1 1
That should resemble the output of MATLAB's contains
.
So, in the end - yes, you need to replicate the functionality by yourself, since strfind
is no exact replacement.
Hope that helps!
EDIT: Use 'isempty'
instead of @isempty
in the cellfun
call to get a faster in-built implementation (see carandraug's comment below).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With