Saving strings of different sizes in one variable

조회 수: 12 (최근 30일)
Tomtom
Tomtom 2017년 10월 27일
댓글: Rik 2017년 10월 27일
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

답변 (1개)

Brendan Hamm
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
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 CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by