필터 지우기
필터 지우기

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 CenterFile Exchange에서 Adding custom doc에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by