MATLAB Answers

# How to use a nested loop for multiple CSV

2 views (last 30 days)
Sue MM on 31 Jan 2019
Edited: Jan on 1 Feb 2019
Hi, I am having some trouble with the following problem. I did some testing and tested 5 materials, 3 times each therefore I have files called a_1, a_2, a_3, b_1, b_2 etc.
I want to create a loop where I can open the csv files, read the first 2 columns for each file column 1 = variable X, column 2 =Variable Y, and then find averages for X and Y variables in 'A', 'B', 'C' (A = a_1, a_2, a_3 etc)
This is the code I have so far but I am having issues with doing the correct mean operations and finding the correct area under graph per file as that is not working
for f = 1:5
Lab = ['a_'; 'b_'; 'c_';'d_';'e_'];
for n = 1:3
filename = ([Lab(f,:),num2str(n),'.csv']);
Test= csvread(filename,1,0);
Extension_Or = Test(:,1);
Force_Or = Test(:,2);
%Subtract noise
Ext_sub = Test(2,1);
F_sub = Test(2,2);
%start at 0
Extension(f,n,:) = Extension_Or(:,1) - Ext_sub;
Force(f,n,:) = Force_Or(:,1) - F_sub;
%Calculate area under graph
Area_Test(f) = trapz(Extension(f,n,:), Force(f,n,:));
end
Extension_Average = mean(Extension);
end

#### 5 Comments

Show 2 older comments
Bob Nbob on 31 Jan 2019
For both trapz and mean you can set a dimension input, which I believe is what you need. Try:
Area_Test(f) = trapz(Extension(f,n,:), Force(f,n,:),1); % For rows dimension
And the same adjustment for rows of mean.
Sue MM on 31 Jan 2019
Unfortunately it still gives me the error: Error using trapz (line 62)
X must be a vector.
Bob Nbob on 31 Jan 2019
Maybe try
Area_Test(f) = trapz([Extension(f,n,:), Force(f,n,:)],1); % Concatonate the two together
Unfortunately, I don't have a perfect solution for you, as I haven't personally used trapz, and don't know how exactly your data should be organized. If the above doesn't work then I would suggest pulling up the documentation of trapz and reviewing it yourself, as that is all I will be able to do.
Feel free to ask any further clarification questions, and I'm sure we will help as we can.

Sign in to comment.

### Community Treasure Hunt

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

Start Hunting!

Translated by