Reputation:
I have a following parameter file in which I want to change values on left hand side starting with gam.dat
till 1 1 1
(against -tail variable, head variable, variogram type
) without changing the format of the file.
This parameter file will be called inside the loop such that each iteration of the loop would require changing the values inside this parameter file.
Reading and writing from a file has always been my weak point. Any help on how this can be done easily? Thanks!
Parameters
**********
START OF PARAMETERS:
gam.dat -file with data
1 1 - number of variables, column numbers
-1.0e21 1.0e21 - trimming limits
gam.out -file for output
1 -grid or realization number
100 1.0 1.0 -nx, xmn, xsiz
100 1.0 1.0 -ny, ymn, ysiz
20 1.0 1.0 -nz, zmn, zsiz
4 30 -number of directions, number of h
1 0 1 -ixd(1),iyd(1),izd(1)
1 0 2 -ixd(2),iyd(2),izd(2)
1 0 3 -ixd(3),iyd(3),izd(3)
1 1 1 -ixd(4),iyd(4),izd(4)
1 -standardize sill? (0=no, 1=yes)
1 -number of gamma
1 1 1 -tail variable, head variable, gamma type
Upvotes: 0
Views: 7419
Reputation: 1039
Something like this might help. Then again it might not be exactly what you're looking for.
fid = fopen(filename as a string);
n = 1;
textline = [];
while( ~feof(fid) ) // This just runs until the end of the file is reached.
textline(n) = fgetl(fid)
// some operations you want to perform?
// You can also do anything you want to the lines here as you are reading them in.
// This will read in every line in the file as well.
n = n + 1;
end
fwrite(fid, textline); // This writes to the file and will overwrite what is already there.
// You always write to a new file if you want to though!
fclose(fid);
The only reason I am suggesting the use of fgetl
here is because it looks like there are specific operations/changes you want to make based on the line or the information in the line. You can also use fread
which will do the same thing but you'll then have to operate on the matrix as a whole after it's built rather than making any modifications to it while reading the data in and building the matrix.
Hope that helps!
More complete example based on the comments below.
fid = fopen('gam.txt');
n = 1;
textline = {};
while( ~feof(fid) ) % This just runs until the end of the file is reached.
textline(n,1) = {fgetl(fid)}
% some operations you want to perform?
% You can also do anything you want to the lines here as you are reading them in.
% This will read in every line in the file as well.
if ( n == 5 ) % This is just an operation that will adjust line number 5.
temp = cell2mat(textline(n));
textline(n,1) = {['newfile.name', temp(regexp(temp, '\s', 'once'):end)]};
end
n = n + 1;
end
fclose(fid)
fid = fopen('gam2.txt', 'w') % this file has to already be created.
for(n = 1:length(textline))
fwrite(fid, cell2mat(textline(n));
end
fclose(fid)
Upvotes: 1