Matlab Concatenate String Variables

Matlab Concatenate String Variables

I know strjoin can be used to concatenate strings, like 'a' and 'b' but what if one of the strings is a variable, like

a=strcat('file',string(i),'.mat')

and I want:

strjoin({'rm',a})

MATLAB throws an error when I attempt this, and it's driving me crazy!

Error using strjoin (line 53) First input must be a string array or cell array of character vectors

5

1 Answer

What version of MATLAB are you using? What is the error? The first input to strjoin needs to be a cell array. Try strjoin({'rm'},a).

Also, before 17a, do:

a = strcat('file', num2str(i),'.mat')

In >=17a do:

a = "file" + i + ".mat";

Here is a performance comparison:

function profFunc

    tic;
    for i = 1:1E5
        a = strcat('file', num2str(i),'.mat');
    end
    toc;

    tic;
    for i = 1:1E5
        a = "file" + i + ".mat";
    end
    toc;
end

>> profFunc
Elapsed time is 6.623145 seconds.
Elapsed time is 0.179527 seconds.
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.