Saving strings of different sizes in one variable
14 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
Brendan Hamm
2017-10-27
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 个评论
Rik
2017-10-27
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!