0

Apologies this is similar to "Loop through files in a folder in matlab" where I've gotten some of the code but I have encountered a problem with this code.

I have many csv files I need to loop over and combine in to one long csv/matrix to analyse, and so I am using the code

files = dir('*.csv'); % Get all input files

for file=files' % loop over files
    csv = csvread(file.name); %get data points
    signal = csv(:,2);
end

The problem I've found is that this only seems to take data from the first file. As in, if:
file1 = [1 2 3]; file2 = [4 5 6];

I get signal = 1 2 3, not 1 2 3 4 5 6.

So, it's as if the loop isn't moving on from the first file, but I thought a for loop was forced to move on, hence my confusion.

TIA

user2587726
  • 169
  • 2
  • 11
  • Does that syntax even work? Even back then? It looks very off to me. I'd suggest using an approach similar to the second answer on the linked question, i.e. loop over an index going through all files. Just save as a matrix instead of cell though, as cells tend to be slow and are not necessary here. – Adriaan Mar 04 '19 at 14:31
  • It works well enough to read and write the first file to "signal" when the script is run, and then typing file.name in the console reads out all the file names, just doesn't seem to "move on" in the for loop. – user2587726 Mar 04 '19 at 14:37

2 Answers2

2

You just need to loop through the files struct

files = dir('*.csv'); % Get all input files
N = numel( files );
signal = cell( N, 1 ); % preallocate output

for ifile = 1:N % loop over files
    csv = csvread( file(ifile).name ); % get data points
    signal{ifile} = csv(:,2);          % store output
end

Then you might combine all the results if you want to operate on them as one

signal = vertcat( signal{:} );
Wolfie
  • 27,562
  • 7
  • 28
  • 55
0

I got there in the end

files = dir('*.csv'); % Get all input files
L = length(files);

csv = csvread(files(1).name);
signal = csv(:,2);

for i = 2:L
   csv = csvread(files(i).name);
   %Did stuff with code
end
user2587726
  • 169
  • 2
  • 11
  • Why didn't you put the first iteration in the loop? It seems as though it's unnecessary to have it outside. – Adriaan Mar 04 '19 at 20:09
  • 1
    The stuff I've done with the code required a special case for i = 1, seemed easier to stick it outside. – user2587726 Mar 05 '19 at 19:25