MATLAB: Write files in.csv format in separate loacation

csvreadxlsread

Using xlsread command I read a large number of .csv files in a loop. I am using the following code to read rawdata and save the output in .csv format(should not ovewrite the existing file)
files=dir('new');
files=files(~[files.isdir]);
n=length(files);
for i=1:n
thisfile=xlsread(fullfile(files(i).folder,files(i).name));
[~,~,rawdata]= xlsread(fullfile(files(i).folder, files(i).name));
A=csvread(rawdata);
A=rawdata(2:end,4);
B=cumsum(cellfun(@double,A));
xlswrite('thisfile.csv', [{'cumulative'}; num2cell(B)], 1, 'D1');
end
However the code just saves the output of the last file in the folder. How do I get the results of n files saved as n different.csv files?

Best Answer

You're saving everything to 'thisfile.csv'. You need to change the filename with each iteration of the for loop. Try something like
files=dir('new');
files=files(~[files.isdir]);
n=length(files);
for i=1:n
thisfile=xlsread(fullfile(files(i).folder,files(i).name));
[~,~,rawdata]= xlsread(fullfile(files(i).folder, files(i).name));
A=csvread(rawdata);
A=rawdata(2:end,4);
B=cumsum(cellfun(@double,A));
[~, fname] = fileparts(files(i).name);
new_filename = fullfile(files(i).folder, [fname '.csv']);
xlswrite(new_filename, [{'cumulative'}; num2cell(B)], 1, 'D1');
end
This will write a CSV file of the same root filename in the same directory as the original file.