How can I store the output value from each for loop?

1 回表示 (過去 30 日間)
Oliver Dandridge
Oliver Dandridge 2016 年 3 月 30 日
編集済み: Oliver Dandridge 2016 年 3 月 30 日
The for loop in the code below reads data from a number of .csv files (approx 250). Everything is working as it ought to be but I cannot store the 'Error' value I have created at the end of the loop. I've looked into examples online and often the use of Error(i) seems to be the solution; however, this doesn't work (I know I don't have an i in my code, instead I use file = files'). Is it something to do with the file = files' statement at the beginning of the loop? Thanks!
clc;
close all;
files = dir('*.csv');
Input_grad = 45;
Disp_lower = 1;
Disp_upper = 1.6;
for file = files'
filename = fopen(file.name);
A = textscan(filename,'%q %q %q','HeaderLines',3,'Delimiter',',')
Time = A{1,1};
Timex = cellfun(@str2num,Time);
Force = A{1,2};
Forcex = cellfun(@str2num,Force);
Disp = A{1,3};
Dispx = cellfun(@str2num,Disp);
Range = (Dispx > Disp_lower & Dispx < Disp_upper );
Position = find(Range==1);
Disp_range = Dispx(Position,:);
Force_range = Forcex(Position,:);
Grad = (Force_range(end))-(Force_range(1))/(Disp_range(end))-(Disp_range(1));
Error = abs(Input_grad - Grad)
fclose(filename);
end

採用された回答

Ced
Ced 2016 年 3 月 30 日
Hi
The file = files' statement is quite crucial, but should be correct like this. The foor loop (by default) will loop through the first row, that's why you need to transpose it to files'. Personally, I would rather do something like
files = dir('*.csv');
N_files = length(files);
for idx = 1:N_files
...
end
so that the orientation of files doesn't matter, but other people would probably do it differently.
To your issue: In each iteration, you are overwriting the value of Error... so in the end, Error will have one value, namely the one from the last file. If you want the error value for all files, you need to create a vector Error of length N_files, and then set each element i to the error from the corresponding file i.
I.e. something like
files = dir('*.csv');
N_files = length(files);
Error_Vector = zeros(N_files,1);
for idx = 1:N_files
%%load and process files
filename = fopen(files(idx).name);
% ... etc
Error_Vector(idx) = abs(Input_grad - Grad);
fclose(filename);
end
  1 件のコメント
Oliver Dandridge
Oliver Dandridge 2016 年 3 月 30 日
編集済み: Oliver Dandridge 2016 年 3 月 30 日
Works perfectly, thank you! I didn't actually realise the ' notation was to transpose something, I just thought it was something to read through a directory. Thanks again.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeAdding custom doc についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by