How do I dynamically generate a variable name for individual saving of temporary data into separate MAT files?

8 ビュー (過去 30 日間)
I'm aware of answers like this and this which do not like the idea of dynamic variable names. Perhaps it is too late in the day, but I am trying to save a single field of a structure as a single variable into a single MAT file, largely because of the large amount of data I have. I have tried the below, which mostly works.
filedate = datestr(now,'yyyymmdd');
for ii = 1:size(car, 1)
filename = [filedate '-' car(ii).NumPlate '-All-TT.mat'];
tempTT = car(ii).Timetable;
save(filename, 'tempTT', '-v7.3')
clearvars tempTT filename;
car(ii).Timetable = [];
end
clear ii car filedate;
However, when you then load these files back into MATLAB, the variable is named 'tempTT' which is extra confusing when they're all named the same, as I'm only using the tempTT variable to take the variable out of the car structure. The car structure contains three fields; name, number plate and timetable. This has previously been convenient, but the files with ALL the data are starting to get unwieldy.
I realise there may already be an answer to this, but I cannot see it. Any guidance, please.

採用された回答

per isakson
per isakson 2017 年 11 月 15 日
編集済み: per isakson 2017 年 11 月 15 日
Doc on save says:
Save the fields of structure s1 as individual variables in a file
called newstruct.mat.
save('newstruct.mat','-struct','s1');
Something like ... ; replace
tempTT = car(ii).Timetable;
save(filename, 'tempTT', '-v7.3')
by
sas.( sprintf('Timetable_%02d',ii)) = car(ii).Timetable;
save( filename, '-struct', '-v7.3', 'sas' )
  1 件のコメント
Ben
Ben 2017 年 11 月 15 日
編集済み: Ben 2017 年 11 月 15 日
Ah. I tried something like that with
temp(ii).(matlab.lang.makeValidName((['car-' car(ii).NumPlate]))) = car(ii).Timetable;
but just could not get it to work even with other configurations. I guess I just gave up trying myself too soon! Thanks for showing me the light. My code now works as intended.
%%Saving Data
filedate = datestr(now,'yyyymmdd');
for ii = 1:size(car, 1)
filename = [filedate '-' car(ii).NumPlate '-All-TT.mat'];
ix35.(matlab.lang.makeValidName((['car-' car(ii).NumPlate]))) = car(ii).Timetable;
save(filename, '-struct', 'ix35', '-v7.3')
clearvars ix35 filename;
car(ii).Timetable = [];
end
clear ii car filedate;

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Import and Analysis についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by