MATLAB: Strfind first occurrence.

MATLABstrfind

str = 'Find the starting indices of a pattern in a character vector'; k = strfind(str,'in') gives, k = 2 15 19 40
any shortcut/direct way to get the first occurrence only. Here in this case: k = 2;

Best Answer

You could use regexp with the 'once' option:
k = regexp(str, 'in', 'once')
However, note that some characters have special meanings in regular expression, so if your search string is completely arbitrary you can't just replace strfind with regexp. For safety you can regexptranslate the search string.
On the other hand, what's stopping you from writing:
k = strfind(str, 'in); k = k(1);
If writing two instructions instead of one bother you, you can always create your own function:
function location = strfindfirst(lookin, lookfor)
location = strfind(lookin, lookfor);
if ~isempty(idx)
location = location(1);
end
end