MATLAB Answers

Creating iteration to make CSVs that do not overwrite

10 views (last 30 days)
Dear MATLAB community,
I recently started to learn MATLAB and would like some support in how to produce multiple non-overwriting CSVs with a loop. I would like to learn the difference between commands that reiterate and overwrite (which I presently have), in comparison to a script which produces unique files.
I wrote a simple script to first load all cell arrays in my directory:
files = dir('/Fastcore/Stem/*.mat');
for i=1:N
Data{1,i} = (sprintf('%s%s','/Fastcore/Stem/', files(i).name));
Next I loop the writing of the variables from my loaded data. These outputs overwrite each other, however I cannot figure out how to produce N csvs into my directory without overwriting:
for i=1:N
Any feedback or suggestions would be appreciated!!!
~Jonathan J.S
Jonathan Josephs-Spaulding
Thank you for this additional feedback and clarification, this makes sense!

Sign in to comment.

Accepted Answer

J. Alex Lee
J. Alex Lee on 12 Jan 2021
I agree with Ive J and their solution will work, but if N>9, you may want to include leading zeros. I'm not sure how to do that with the string addition operators, but you can also use the sprintf mechanism you already know about
csvpath = sprintf('/Fastcore/Test/RxnsNames-%03d.csv',i)
Alternatively, you maybe you want to preserve the original mat file's base name.
files = dir('/Fastcore/Stem/*.mat');
% one loop
for i = 1:length(files)
% choose one of the csv naming schemes
[~,base] = fileparts(files(i).name);
csvpath = fullfile(files(i).folder,sprintf("%s.csv",base))
% % alternative csv naming
% csvpath = fullfile(files(i).folder,sprintf("RxnsNames%03d.csv",i));
% load mat file into structure to avoid ambiguity pointed out by Ive J
matpath = fullfile(files(i).folder,files(i).name);
celldata = load(matpath)
% you don't necessarily need this intermediary, but in case you want to do further post-processing later
tabledata = cell2table(celldata.tissueModel(1).rxns);
% now you don't have to modify this part if you change you mind about anything above
  1 Comment
Jonathan Josephs-Spaulding
A very nice solution and alternative, thank you for adding this !

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!