2

I'm following an online course to learn and practice matlab. In the course, the guys writes:

basefilename = 'testfile';
filename = [basefilename num2str(1) ".mat"]

and Matlab returns:

testfile1.mat

However, when enter the same input, I get the following as an output:

filename = 

  1×3 string array

    "testfile"    "1"    ".mat"

I tried a more usual concatenating method by inputting

filename = [basefilename + "1" + ".mat"]

And go the correct output:

testfile1.mat

However, when changing the "1" to num2str(1) (in order to replace the number by a variable that can vary in a for loop later on):

filename = [basefilename + num2str(1) + ".mat"]

I get a completely different output:

filename = 

  1×8 string array

    "165.mat"    "150.mat"    "164.mat"    "165.mat"    "151.mat"    "154.mat"    "157.mat"    "150.mat"

I was wondering if someone could explain why each input methods returns such drastically different outputs. It seems to me like all three methods should return the same thing...

3
  • 4
    Maybe mixing of character arrays ('test') and actual strings ("test") is a problem here? See Create String Arrays from the MATLAB documentation for further reading. Commented Oct 30, 2019 at 11:55
  • The online course likely is written for Octave, which treats " as if it were '. You should translate all their double quotes to single quotes. Commented Oct 30, 2019 at 13:04
  • 1
    Taking a wild guess at your workflow, I think you could benefit from the implicit conversion that plus with strings can do. "basefilename" + 1 + ".mat". If you wanted to create an array of filenames you could do "basefilename" + (1:10)' + ".mat" Commented Oct 30, 2019 at 20:28

2 Answers 2

2
basefilename = 'testfile';

basefilename is a char array (note the single quotes). Double quotes implies a single string variable.

filename = [basefilename num2str(1) '.mat']

will yield the desired results by concatenating arrays of char's while

filename = ["stuff" ".mat"]

will generate an array of 2 strings, and as you noted

filename = ["stuff" + ".mat"]

yields a single concatenated variable of type string.

The example you showed with

filename = ['chars'  ".strings"]

filename = ['chars' + "strings"]

will cast the char array (single quoted) to a string and then perform the assignment.

Sign up to request clarification or add additional context in comments.

Comments

0

Can you try remove the '+' and the "". So:

filename = [basefilename num2str(1) '.mat']

The '+' isn't used for concatenating in MATLAB, and there is a difference between ' and " in MATLAB (String indexing in MATLAB: single vs. double quote)

Comments

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.