0

我有一个以下参数文件,我想在其中更改左侧的值,从gam.datuntil 1 1 1(反对-tail variable, head variable, variogram type)开始,而不更改文件的格式。

此参数文件将在循环内调用,因此循环的每次迭代都需要更改此参数文件内的值。

从文件读取和写入一直是我的弱点。有关如何轻松完成此操作的任何帮助?谢谢!

                  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
4

1 回答 1

1

这样的事情可能会有所帮助。话又说回来,它可能不是您正在寻找的东西。

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);

我建议使用fgetl这里的唯一原因是因为看起来您想要根据行或行中的信息进行特定的操作/更改。您也可以使用freadwhich 将执行相同的操作,但是您必须在构建矩阵后对整个矩阵进行操作,而不是在读取数据和构建矩阵时对其进行任何修改。

希望有帮助!

基于以下评论的更完整示例。

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)
于 2012-07-16T15:02:17.327 回答