How am I supposed to access, let's say, the first character of every member of a string array? For example, I would like to capitalize the first letter of each word.
str = ["house", "stone", "summer"]
You can do it using conventional slicing. To get a capital of a letter I used upper
function
for i=1:size(str,2)
str{i}(1)=upper(str{i}(1))
end
I think the best solution is to use extractBefore and extractAfter:
upper(extractBefore(str,2)) + extractAfter(str,1);
Here is a performance benchmark:
function profFunc
str = ["house", "stone", "summer"];
n = 1E5;
% My solution
tic;
for i = 1:n
str = upper(extractBefore(str,2)) + extractAfter(str,1);
end
toc;
% Mikhail Genkin's solution
tic;
for i = 1:n
for i=1:size(str,2)
str{i}(1)=upper(str{i}(1));
end
end
toc;
% EdR's Solution
tic;
for i = 1:n
str = string(cellfun(@(x) [upper(x(1)) x(2:end)], str, 'UniformOutput', false));
end
toc
end
>> profFunc
Elapsed time is 0.121556 seconds.
Elapsed time is 1.034617 seconds.
Elapsed time is 10.319375 seconds.
The following code will do what you want:
string(cellfun(@(x) [upper(x(1)) x(2:end)], str, 'UniformOutput', false))
cellfun
applies the anonymous function following it to the variable str.
The anonymous function just returns the concatenation of the upper case of the first element followed by the rest of the string.
string
converts the cell array back to a string array.
Edited: to convert back to a string array as requested in the comments.
The other answer may produce easier to read code, however.
Adapting @matlabbit's answer to take advantage of the fact that recent versions of MATLAB can emit string
arrays from arrayfun
, you could write
capitalize = @(s) upper(extractBefore(s, 2)) + extractAfter(s, 1)
arrayfun(capitalize, ["house", "stone", "summer"])
Two small somewhat pedantic comments on this post:
proper syntax would be:
arrayfun(@capitalize, ["house", "stone", "summer"]);
Given the vectorized nature of the functions involved (upper, extractBefore, extractAfter) the arrayfun is redundant, ie a simple function call should work:
capitalize(["house", "stone", "summer"]);
Note that these remarks have been tested in version R2020b although it might stand also for an earlier version. I have not tested it myself.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.