How can I store the output value from each for loop?
1 次查看(过去 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
0 个评论
采纳的回答
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Adding custom doc 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!