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

조회 수: 125 (최근 30일)
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
Jeffrey Clark
Jeffrey Clark 2022년 6월 11일
@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 2022년 6월 13일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2022년 6월 11일
편집: Stephen23 2022년 6월 11일
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by