Loop code for many data files and save

I wrote this code, which load a file text2.dat, to use its data to calculate velocity.
I have many files text3.dat test4.dat...
I want to make this code to load all files and calculate velocity for each file, then save it separatly (vel1.dat, vel2.dat, vel3.dat....)
data=load('test2.dat');
time= data(:,1);
x= data(:,2);
y= data(:,3);
x=x*(3e-7);
y=y*(3e-7);
Vx = gradient(x, time);
Vy = gradient(y, time);
for i=1:n-1
vel_x(i) = ((x(i)-x(i+1)))/(time(i)-time(i+1));
%t(i)= x(i)-x(i+1);
%s= gradient (x);
vel_y(i) = ((y(i)-y(i+1)))/(time(i)-time(i+1));
vel(i) = sqrt(vel_x(i)*vel_x(i)+ vel_y(i)* vel_y(i))
V(i) = sqrt(Vx(i)^2 + Vy(i)^2);
end
%V=V';
indices = find(abs(vel)>2e-4);
vel(indices) = [];
V=V';

 Accepted Answer

6 Comments

thank you this is how to load sequentially numbered files.
But how Can I apply my calculation for every file? and save them sequentially too
numfiles = 83; %adjust as needed
for K = 1 : numfiles
infilename = sprintf('test%d.dat', K);
outfilename = sprintf('vel%d.dat', K);
data = load(infilename);
time= data(:,1);
x= data(:,2);
y= data(:,3);
x=x*(3e-7);
y=y*(3e-7);
Vx = gradient(x, time);
Vy = gradient(y, time);
for i=1:n-1
vel_x(i) = ((x(i)-x(i+1)))/(time(i)-time(i+1));
%t(i)= x(i)-x(i+1);
%s= gradient (x);
vel_y(i) = ((y(i)-y(i+1)))/(time(i)-time(i+1));
vel(i) = sqrt(vel_x(i)*vel_x(i)+ vel_y(i)* vel_y(i))
V(i) = sqrt(Vx(i)^2 + Vy(i)^2);
end
%V=V';
indices = find(abs(vel)>2e-4);
vel(indices) = [];
V=V';
save(outfilename, 'vel', '-ascii', '-double');
save(outfilename, V, '-ascii', '-double', '-append')
end
Thank you very much it works!
Just one thing, I want to add the Time colum in the output file
I tried with
vel = transpose(vel);
save(outfilename,'time' 'vel', '-ascii', '-double');
but didn't work
you missed a comma after 'time'
You are deleting some of the vel entries. Remember to delete the corresponding time entries.
You should probably make a variable that has time in the first column and vel in the second column, and save that.
I see, indeed you are right.
But when I make the loop
for i=1:n
I got this error
Error in veloc (line 16)
vel_x(i) = ((x(i)-x(i+1)))/(time(i)-time(i+1));
For the variable I tried doing something like this:
A=[time x y vel];
But I got this
Error using horzcat
Dimensions of matrices being concatenated are not consistent.
Error in veloc (line 25)
A=[time x y vel];

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 20 Jul 2021

Commented:

on 21 Jul 2021

Community Treasure Hunt

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

Start Hunting!