How do I rename a table to a string
조회 수: 14 (최근 30일)
이전 댓글 표시
I am importing data from a bunch of .csv files. Each csv file has a unique name. I am importing the files so I can use them in another matlab program. But i would like each .mat data file to have the name of the .csv file i import. I can create the timetable i want. i have a string with the .csv file name. but i dont know how to "rename" the file to the .csv string name. here is the code. in the example below, i dont want all the files to be named EURUSDM30
%%Import data from text file.
%%Select file to import
defaultFileName = fullfile(pwd, '*.csv');
[importFile, folder] = uigetfile(defaultFileName, 'Select a file');
%%Format for each line of text:
formatSpec = '%{yyyy.MM.dd}D%{HH:mm}D%f%f%f%f%f%[^\n\r]';
%%Open the text file.
fileID = fopen(strcat(folder,importFile),'r');
%%Read columns of data according to the format.
dataArray = textscan(fileID, formatSpec, 'Delimiter', ',', 'TextType', 'string', 'EmptyValue', NaN, 'ReturnOnError', false);
%%Close the text file.
fclose(fileID);
%%Create output table
NewTable = table(dataArray{1:end-1}, 'VariableNames',
{'DateTime','Time','Open','High','Low','Close','Volume'});
NewTable.DateTime.Format = 'dd.MM.uuuu HH:mm';
NewTable.DateTime = NewTable.DateTime + timeofday(NewTable.Time);
NewTable.Time = [];
EURUSDM30 = table2timetable(NewTable);
%%Clear temporary variables
clearvars filename delimiter formatSpec fileID dataArray ans;
댓글 수: 0
채택된 답변
Walter Roberson
2018년 6월 21일
filename = fullfile(folder, importFile);
fileID = fopen(filename, 'r');
...
[folder, basename, ~] = fileparts(filename);
newname = fullfile(folder, [basename '.mat']);
save(newname, 'EURUSDM30');
This would create the variable as named EURUSDM30 within each of the .mat files.
If you need the variable name to be the same as the .mat name, then there are a couple of extra steps to take. (But typically it is easier to work with the files when the variable name is consistent instead of when it is named after the file.)
댓글 수: 0
추가 답변 (1개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Text Files에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!