MATLAB中使用strjoin拼接含变量的字符串报错问题求助
strjoin Error in MATLAB Got it, let's break down why you're hitting this error and how to fix it right away.
Why the Error Happens
The error message spells it out clearly: strjoin requires its first input to be either a string array or a cell array of character vectors (char type). Your problem is that the cell array {'rm', a} mixes two incompatible types:
'rm'is a standard character vector (chartype)ais astringtype (since you usedstring(i)instrcat, which outputs a string object)
Mixing these in the same cell array violates strjoin's input rules, hence the error.
Solution 1: Convert a to a Character Vector
If you want to stick with a cell array, just convert your string variable a to a char using the char() function:
% Example with a sample value for i i = 1; a = strcat('file', string(i), '.mat'); a_char = char(a); % Convert string to char vector command = strjoin({'rm', a_char});
Solution 2: Use a String Array Instead of a Cell Array
MATLAB's string arrays are more intuitive for this kind of work. Wrap your elements in double quotes ("") to create a string array, which strjoin handles flawlessly:
i = 1; a = strcat('file', string(i), '.mat'); command = strjoin(["rm", a]);
Bonus: A Cleaner String Splicing Method
You don't even need strcat here—MATLAB lets you directly concatenate strings and numbers with the + operator, which is far more readable:
i = 1; a = "file" + i + ".mat"; % Direct, clean string concatenation command = strjoin(["rm", a]);
All these approaches will resolve the error and give you the joined string you need.
内容的提问来源于stack exchange,提问作者user3433489

