JuliAugust
JuliAugust

Reputation: 11

Count up variable/table name with while loop

I'm reading multiple tables with the same measurement variable. I want to compare the variables of tables with each other. Because there are so many tables and with each one I'm doing the same things, I wanted to automate the process with a while loop. But I don't know how to replace the 1 (in the variable and the table) with the k.

data_1 = readtable('file_xy')
data_2 = readtable('file_zy')
data_3 = readtable('file_zz')
...

k=1

while k < 50
 Temp_1 = mean([data_1.tempx(:), data_1.tempz(:)], 2)
 p_1 = mean([data_1.px(:), data_1.pz(:)], 2)
 k = k+1
end

How can I read and process all my tables automatically?

Upvotes: 1

Views: 135

Answers (1)

Adriaan
Adriaan

Reputation: 18177

As you've noticed, copying lines of codes tens (let alone hundreds or thousands) of times to do the same thing can (and should!) be automated in most cases. What you're doing is creating dynamic variable names, which is bad, very bad, not to mention requiring you to copy-paste the same line of code 50 times. Instead, read all files using a simple loop.

There're several other, smaller, points of improvement, I'll outline them below in the code block.

% First, select the directory where your files are
input_dir = "C:\path\to\your\folder";
% Read the entire directory, searching for files of your type
% change .txt to whatever file type you have.
file_list = dir([input_dir '\*.txt']);

% ROWS comes from the amount of rows in your table files
% Pre-allocate output arrays for memory efficiency
Temp = zeros(ROWS, numel(file_list));
p = zeros(ROWS, numel(file_list));

% Use a for loop, since you know how many elements there are
for idx = 1:numel(file_list)
    % Read the files in order
    tmp_data = readtable([input_dir file_list(idx).name)]);
    Temp(:,idx) = mean([tmp_data .tempx(:), tmp_data .tempz(:)], 2)
    p(idx,:) = mean([tmp_data .px(:), tmp_data .pz(:)], 2)
end

Temp and p are now both matrices, with your original Temp_1 in Temp(:,1), p_1 in p(:,1) etc. This assumes Temp and p to be rows, as per the dimensional argument in mean.

You might have to play around with the dimensions, as I don't know your data size. But in general, this should give you a good starting point on how to read multiple files and store them efficiently, using preallocation.
Note that whilst you can use a while loop, given that you have a fixed number of iterations, being the number of files, there's not much need to. I'd only use a while loop if the number of iterations is not fixed, for example in optimisation problems, where the code stops based on reaching some condition.

Finally: MATLAB has great documentation including lots of examples. If you don't understand a function, go to there as a first point of access.

Good luck!

Upvotes: 2

Related Questions