SYNTAX
str = substr(s,i,j)
str = substr(s,i,j,length_or_index)
DESCRIPTION
str = substr(s,i,j) returns the extracted part of s with length j beggining from i; or an empty vector if j < i or .
str = substr(s,i,j,length_or_index) the argument j is treated as the index of the last position of the substring inside s if length_or_index is equal to 'index'.
EXAMPLES
Outputs the substring from the second index position with a length of 3 chars.
str = substr('12345',2,3)
str =
'234'
Outputs the substring from the second to the third index position.
str = substr('12345',2,3,'index')
str =
'23'
INPUT ARGUMENTS
s — Input string
character vector or string scalar
String to extract a substring.
Data Types: string
i — Initial index
positive integer number
Number of the initial index inside str.
Data Types: double | single | int64 | int32 | int16 | int8
j — Length / End index
positive real number
Length of the output string if i > 0 or number of the end index inside str if length_or_index == 'index'.
Data Types: double | single | int64 | int32 | int16 | int8
length_or_index — Length or index
'length' (default) | 'index'
A string that interprets the input j as length when it is equal to 'length'.
or as an index when it is equal to 'index'.
Data Types: string
OUTPUT ARGUMENT
str — Substring
character vector or string scalar
String inside s.
Fernando Freitas Alves (2021). substr (https://www.mathworks.com/matlabcentral/fileexchange/59560-substr), MATLAB Central File Exchange. Retrieved .
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!Create scripts with code, output, and formatted text in a single executable document.
Slow and unnecessary.
Rather than downloading this third-party function, all you need it to use basic MATLAB indexing. Using MATLAB indexing is simpler, faster, neater, easier to debug, is standard practice, and does not rely on any third-party functions. It is this simple:
>> str = '1':'5';
>> str(2:5)
ans = 2345
>> str(2:3)
ans = 23
Note that calculating those numeric indices will be much faster than this submission. Why? Because this function is made extremely slow by the usage of EVAL, and the multiple numeric-to-character conversions that are required for that. The author might like to learn why good (i.e. neat, efficient, robust code) avoids using EVAL:
<https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval>