MATLAB: How to rename a table to a string

MATLABrename table

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.
%%Create output table
NewTable = table(dataArray{1:end-1}, 'VariableNames',
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;

Best Answer

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.)