Matlab strcat function troubles with spaces - matlab

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 ')

Related

What does '-' mean in matlab code

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

How to make title interpret only part of a title string in Matlab

I'm creating a plot where I want to combine two strings into a title. I want to color the other part of my string. Here is my code (it will explain itself better):
title([csv_name ', {\color{blue}Bowel AUC: ' num2str(bowelAUC) ' }'])
In the variable csv_name I have a filename containing underscore _ characters and in the variable bowelAUC I have a number. I can color only part of my title string by using the guide in this post, that is using tex, but the problem now is that tex interpreter would also interpret the csv_name variable and I don't want this. Here you can see what I get:
The filename looks like this: ExportedPressure_130A_10-29-2014.csv
So I want title to interpret only the second part of my title, not the first...how to do this?
You need to replace _ by \_ so that TeX interprets them correctly. To do that you can use regexprep (note that within regexprep both characters are escaped again):
csv_name_escaped = regexprep(csv_name, '\_', '\\\_');
title([csv_name_escaped ', {\color{blue}Bowel AUC: ' num2str(bowelAUC) ' }'])

print cells type in Matlab

I have a cell array like:
>>text
'Sentence1'
'Sentence2'
'Sentence3'
Whenever I use
sprintf(fid,'%s\n',text)
I get an error saying:
'Function is not defined for 'cell' inputs.'
But if I put :
sprintf(fid,'%s\n',char(text))
It works but in the file appears all the sentences mixed all together like with no sense.
Can you recommend me what to do?
Whener I put text I get:
>>text
'Title '
'Author'
'comments '
{3x1} cell
That is why I can not use text{:}.
If you issue
sprintf('%s\n', text)
you are saying "print a string with a newline. The string is this cell array". That's not correct; a cell-array is not a string.
If you issue
sprintf('%s\n', char(text))
you are saying "print a string with a newline. The string is this cell array, which I convert to character array.". The thing is, that conversion results in a single character array, and sprintf will re-use the %s\n format only for multiple inputs. Moreover, it writes that single character array by column, meaning, all characters in the first column, concatenated horizontally with all characters from the second column, concatenated with all characters from the third column, etc.
Therefore, the approprate call to sprintf is something with multiple inputs:
sprintf(fid, '%s\n', text{:})
because the cell-expansion text{:} creates a comma-separated list from all entries in the cell-array, which is exactly what sprintf/fprintf expects.
EDIT As you indicate:, you have non-char entries in text. You have to check for that. If you want to pass only the strings into fprintf, use
fprintf(fid, '%s\n', text{ cellfun('isclass', text, 'char') })
if that {3x1 cell} is again a set of strings, so you want to write all strings recursively, then just use something like this:
function textWriter
text = {...
'Title'
'Author'
'comments'
{...
'Title2'
'Author2'
'comments2'
{...
'Title3'
'Author3'
'comments3'
}
}
}
text = cell2str(text);
fprintf(fid, '%s\n', text{:});
end
function out = cell2str(c)
out = {};
for ii = c(:)'
if iscell(ii{1})
S = cell2str(ii{1});
out(end+1:end+numel(S)) = S;
else
out{end+1} = ii{1};
end
end
end

How to add \ before all special characters in MATLAB?

I am trying to add '\' before all special characters in a string in MATLAB, could anyone please help me out. Here is the example:
tStr = 'Hi, I'm a Big (Not So Big) MATLAB addict; Since my school days!';
I want this string to be changed to:
'Hi\, I\'m a Big \(Not so Big \) MATLAB addict\; Since my school days\!'
The escape character in Matlab is the single quote ('), not the backslash (\), like in C language. Thus, your string must be like this:
tStr = 'Hi\, I\''m a Big (Not so Big ) MATLAB addict\; Since my school days!'
I took the list of special charecters defined on the Mathworks webpage to do this:
special = '[]{}()=''.().....,;:%%{%}!#';
tStr = 'Hi, I''m a Big (Not So Big) MATLAB addict; Since my school days!';
outStr = '';
for l = tStr
if (length(find(special == l)) > 0)
outStr = [outStr, '\', l];
else
outStr = [outStr, l];
end
end
which will automatically add those \s. You do need to use two single quotes ('') in place of the apostrophe in your input string. If tStr is obtained with the function input(), or something similar, this will procedure will still work.
Edited:
Or using regular expressions:
regexprep(tStr,'([[\]{}()=''.(),;:%%{%}!#])','\\$1')

Adding a substring to each line in a string in MATLAB

Say I have a string in a variable in MATLAB like the following:
this is the first line
this is the second line
this is the third line
I would like to add a fixed string at the beginning of each line. For example:
add_substring(input_string, 'add_this. ')
would output:
add_this. this is the first line
add_this. this is the second line
add_this. this is the third line
I know I can do this by looping through the input string, but I am looking for a more compact (hopefully vectorized) way to do this, perhaps using one of MATLAB built-ins such as arrayfun accumarray.
The strcat function is what you're looking for. It does vectorized concatenation of strings.
strs = {
'this is the first line'
'this is the second line'
'this is the third line'
}
strcat({'add_this. '}, strs)
With strcat, you need to put 'add_this. ' in a cell ({}) to protect it from having its trailing whitespace stripped, which is strcat's normal behavior for char inputs.
Assuming your strings are stored in a cell array then cellfun will do what you want, e.g.
s = {'this is the first line', 'this is the second line', 'this is the third line'};
prefix = 'add_this. ';
res = cellfun(#(str) strcat(prefix, str), s, 'UniformOutput', false);