Saving strings of different sizes in one variable

11 views (last 30 days)
Tomtom
Tomtom on 27 Oct 2017
Commented: Rik on 27 Oct 2017
Hey everybody,
I would like to save the path of different files in one variable as a string.
I have files in different directories. That look like this
name_1 = 'folder1 xxx\name 1.txt'
name_2 = 'folder2 xxxxxxx\name 2.txt'
name_3 = 'folder3 x\name 3.txt'
the .txt file consist of a comma separated value text that I have to read and plot the data from. At the moment I save their names separately in a variable name_1..X. The problem is that I have to give my function the names
loaddata_and_plot(name_1,name_2,name_3......)
now my whole screen is full of this variables (name_1 etc.) Isn't there a simpler way? For a lot of my purposes one variable with every name in it would be the best. I tried chars, strings, etc. but I can't get it to work and I searched far and wide here.
Especially for loops that would be fantastic. e.g. I would like to show the file name without path ('name 1.txt') as legend by searching the "\" and cut the string to just the last part.
Help would really be appreciated

Answers (1)

Brendan Hamm
Brendan Hamm on 27 Oct 2017
This is where the cell data type is used.
names = {'folder1 xxx\name 1.txt';'folder2 xxxxxxx\name 2.txt';name_3 = 'folder3 x\name 3.txt'};
Now when you want to use the underlying char (note that string is a different datatype), you can extract it by indexing with curly brackets:
firstName = names{1};
  1 Comment
Rik
Rik on 27 Oct 2017
And this is where you should use fileparts:
[filepath,name,ext] = fileparts(filename)
Whatever you do, don't use eval. Stephen Cobeldick is very pasionate about this topic (and with good reason), so I have taken the liberty of adapting some of his thoughts on this topic: Introspective programing (eval and other functions like it) is slow, and the MATLAB documentation warns specifically against it. Using eval is slow, makes debugging difficult, and removes all code helper tools (code checking, syntax hints, code completion, variable highlighting, etc.). A longer discussion can be found here. If you are not an expert and you think you need eval, there are probably better solutions to your problem.

Sign in to comment.

Categories

Find more on Scope Variables and Generate Names in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!