What does '-' mean in matlab code - matlab

Can some one explain what this line here does? This is part of an old matlab code I need to reuse for my work
matdir = [params.ariens '-' num2str(dirtimes(ii))];
I'm especially confused about the '-' part. Thanks a lot in advance.

Single quotes are used to create a string literal so '-' simply creates a string containing the hyphen character. In MATLAB, [ ... ] performs horizontal concatenation so the line that you have shown concatenates the string stored in params.ariens, the character '-' and the number dirtimes(ii) converted to a string using num2str to creat one long string made up of those three strings.
For example:
c = ['abc', '-', 'def']
% abc-def
class(c)
% char
d = ['abc', '-', num2str(10)]
% abc-10

Related

How to convert an string array into a character array in Matlab?

Suppose that we have an string array in Matlab like bellow:
a='This is a book'
How can we convert the above string array into a character array by a function in Matlab like bellow?
b={'T' 'h' 'i' 's' ' ' 'i' 's' ' ' 'a' ' ' 'b' 'o' 'o' 'k'}
Your a is not a string array; it's a character array (which also used to be called a string, but starting from R2016b that term has a different meaning). Your b is not a character array, it's a cell array that contains characters.
Anyway, to convert from a to b, use num2cell:
a = 'This is a book';
b = num2cell(a);
If you really really want to convert string (introduced since R2016b) to char array, this is how you do.
s = "My String"; % Create a string with ""
c = char(s); % This is how you convert string to char.
isstring(c)
ans =
logical
0
ischar(c)
ans =
logical
1

Function to split string in matlab and return second number

I have a string and I need two characters to be returned.
I tried with strsplit but the delimiter must be a string and I don't have any delimiters in my string. Instead, I always want to get the second number in my string. The number is always 2 digits.
Example: 001a02.jpg I use the fileparts function to delete the extension of the image (jpg), so I get this string: 001a02
The expected return value is 02
Another example: 001A43a . Return values: 43
Another one: 002A12. Return values: 12
All the filenames are in a matrix 1002x1. Maybe I can use textscan but in the second example, it gives "43a" as a result.
(Just so this question doesn't remain unanswered, here's a possible approach: )
One way to go about this uses splitting with regular expressions (MATLAB's strsplit which you mentioned):
str = '001a02.jpg';
C = strsplit(str,'[a-zA-Z.]','DelimiterType','RegularExpression');
Results in:
C =
'001' '02' ''
In older versions of MATLAB, before strsplit was introduced, similar functionality was achieved using regexp(...,'split').
If you want to learn more about regular expressions (abbreviated as "regex" or "regexp"), there are many online resources (JGI..)
In your case, if you only need to take the 5th and 6th characters from the string you could use:
D = str(5:6);
... and if you want to convert those into numbers you could use:
E = str2double(str(5:6));
If your number is always at a certain position in the string, you can simply index this position.
In the examples you gave, the number is always the 5th and 6th characters in the string.
filename = '002A12';
num = str2num(filename(5:6));
Otherwise, if the formating is more complex, you may want to use a regular expression. There is a similar question matlab - extracting numbers from (odd) string. Modifying the code found there you can do the following
all_num = regexp(filename, '\d+', 'match'); %Find all numbers in the filename
num = str2num(all_num{2}) %Convert second number from str

Extract character between two specified characters of a string using Matlab

I have a string and want to extract the numbers between the character 'w' and 's'. The positions of the the characters vary between different strings.
For example:
s = '1w12s01'
desired result: '12'
and
s = '102w22s21'
desired result: '22'
It can also be done using a regular expression with lookahead and lookbehind:
regexp(s,'(?<=w).*(?=s)','match')
The function strfind will do this easily enough. This will work as long as the number is always directly between a 'w' and and 's', both are only in the target string once, and the number you're after is the only thing between those two characters.
s = '102w22s21';
r = s((strfind(s, 'w')+1):(strfind(s, 's')-1));
Use this:
e = extractBetween(s,'w','s');

Working string in MATLAB

I have the following string in MATLAB, for example
##%%F1_USA(40)_u
and I want
F1_USA_40__u
Does it has any function for this?
Your best bet is probably regexprep which allows you to replace parts of a string using regular expressions:
s_new = regexprep(regexprep(s, '[()]', '_'), '[^A-Za-z0-9_]', '')
Update: based on your updated comment, this is probably what you want:
s_new = regexprep(regexprep(s, '^[^A-Za-z0-9_]*', ''), '[^A-Za-z0-9_]', '')
or:
s_new = regexprep(regexprep(s, '[^A-Za-z0-9_]', '_'), '^_*', '')
One way to do this is to use the function ISSTRPROP to find the indices of alphanumeric characters and replace or remove the others accordingly:
>> str = '##%%F1_USA(40)_u'; %# Sample string
>> index = isstrprop(str,'alphanum'); %# Find indices of alphanumeric characters
>> str(~index) = '_'; %# Set non-alphanumeric characters to '_'
>> str = str(find(index,1):end) %# Remove any leading '_'
str =
F1_USA_40__u %# Result
If you want to use regular expressions (which can get a little more complicated) then the last suggestion from Tamas will work. However, it can be greatly simplified to the following:
str = regexprep(str,{'\W','^_*'},{'_',''});

Matlab strcat function troubles with spaces

I'm trying to accomplish this:
strcat('red ', 'yellow ', 'white ')
I expected to see "red yellow white", however, I see "redyellowwhite" on the command output. What needs to be done to ensure the spaces are concatenated properly? Thanks in advance.
Although STRCAT ignores trailing white space, it still preserves leading white space. Try this:
strcat('red',' yellow',' white')
Alternatively, you can just use the concatenation syntax:
['red ' 'yellow ' 'white ']
From the matlab help page for strcat:
"strcat ignores trailing ASCII white space characters and omits all such characters from the output. White space characters in ASCII are space, newline, carriage return, tab, vertical tab, or form-feed characters, all of which return a true response from the MATLAB isspace function. Use the concatenation syntax [s1 s2 s3 ...] to preserve trailing spaces. strcat does not ignore inputs that are cell arrays of strings. "
In fact, you can simply use the ASCII code of space: 32. So, you can solve the problem like this:
str = strcat('red', 32, 'yellow', 32, 'white');
Then you will get str = 'red yellow white'.
You can protect trailing whitespace in strcat() or similar functions by putting it in a cell.
str = strcat({'red '}, {'yellow '}, {'white '})
str = str{1}
Not very useful in this basic example. But if you end up doing "vectorized" operations on the strings, it's handy. Regular array concatenation doesn't do the 1-to-many concatenation that strcat does.
strs = strcat( {'my '}, {'red ','yellow ','white '}, 'shirt' )
Sticking 'my ' in a cell even though it's a single string will preserve the whitespace. Note you have to use the {} form instead of calling cellstr(), which will itself strip trailing whitespace.
This is all probably because Matlab has two forms of representing lists of strings: as a cellstr array, where all whitespace is significant, and as a blank-padded 2-dimensional char array, with each row treated as a string, and trailing whitespace ignored. The cellstr form most resembles strings in Java and C; the 2-D char form can be more memory efficient if you have many strings of similar length. Matlab's string manipulation functions are polymorphic on the two representations, and sometimes exhibit differences like this. A char literal like 'foo' is a degenerate one-string case of the 2-D char form, and Matlab's functions treat it as such.
UPDATE: As of Matlab R2019b or so, Matlab also has a new string array type. Double-quoted string literals make string arrays instead of char arrays. If you switch to using string arrays, it will solve all your problems here.
or you can say:
str = sprintf('%s%s%s', 'red ', 'yellow ', 'white ')