MATLAB:大写字符串数组中的第一个字母

And*_*ndi 4 string matlab

我应该如何访问,比方说,字符串数组的每个成员的第一个字符?例如,我想将每个单词的第一个字母大写.

str = ["house", "stone", "summer"]
Run Code Online (Sandbox Code Playgroud)

Mik*_*kin 6

你可以使用传统的切片来做到这一点.为了获得一封信的大写,我使用了upper函数

for i=1:size(str,2)
    str{i}(1)=upper(str{i}(1))
end
Run Code Online (Sandbox Code Playgroud)


mat*_*bit 5

我认为最好的解决方案是使用extractBefore和extractAfter:

upper(extractBefore(str,2)) + extractAfter(str,1);
Run Code Online (Sandbox Code Playgroud)

这是一个性能基准:

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.
Run Code Online (Sandbox Code Playgroud)