1

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
  • 3
    Why not just use strcat again? strjoin is, per the documentation, for joining strings contained in an array. Commented Apr 20, 2018 at 2:14
  • sprintf() will also do the job. Commented Apr 20, 2018 at 3:34
  • It helps to include the error. Commented Apr 20, 2018 at 4:52
  • Sorry, the error is there now Commented Apr 20, 2018 at 13:34
  • RE: your edit, MATLAB's string and char classes are not the same. Per strcat's documentation, if any input is a string, then the output is a string, so a is a string. 'rm' is not a string, it's a character vector, so the cell array you edited in is not a cell array of character vectors. I don't agree with MATLAB's unyielding differentiation of string and char, but the error message is sufficiently explanatory. strcat('rm', a) still works fine. Commented Apr 20, 2018 at 14:07

1 Answer 1

5

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.
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I didn't realize I could use '+' in recent versions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.