How to save tables as .mat files without having to type the filename manually?

119 views (last 30 days)
I want to save a table as a .mat file, but the name I want to give it is stored as a character in my workspace.
I wrote a code which creates tables from .csv files, which then [the tables] are being saved as .mat files. I know the classic way of saving tables as .mat manually.
save table.mat T
But my code works as a loop and I would like to use it for other projects. Thats why I want the process to be automatic.
My code is:
files = dir('*.csv');
for i=1:length(files)
filenames = {files.name};
T=xlsread(files(i).name);
a=filenames{i};
end
Now I want the code to firstly separate the actual name from ".csv", and then to somehow use the actual name as name how the .mat file will be saved. So if for example my csv-file is 'LCN_10.csv', I want my .matfile to be saved as 'LCN_10.mat' without having to type the name manually.
I hope that you understood what I meant and would be very pleased if somebody could help me out.
  3 Comments
Jeffrey Clark
Jeffrey Clark on 11 Jun 2022
@Leo Hastrich, use matfile or save(filename[, ]) not save filename. You can create a string or char array of whatever you want for the filename in these.
Peter Perkins
Peter Perkins on 13 Jun 2022
What Jeffrey is describing is what's known as "command dual".
fun someText
passes "someText" to fun, the equivalent of fun("someText"). In your case, you cannot use the command dual form, because there's no command dual equivalent to fun(someVar)
fun someVar
is equivalent to fun("someVar")
But also, don't use xlsread. Use readtable or readmatrix.

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 11 Jun 2022
Edited: Stephen23 on 11 Jun 2022
The solution is to use function syntax, not command syntax:
as explained here:
and also explained in the SAVE documentation here:
Command syntax is convenient at when playing around in the command window, but is less useful in actual code.
S = dir('*.csv');
for k = 1:numel(S)
T = xlsread(S(k).name);
[~,F] = fileparts(S(k).name);
F = sprintf('%s.mat',F);
save(F,'T') % <----------- function syntax !!!
end

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!