2017-02-25 14 views
0

MATLABのテキストファイルの文字列を置き換えたいと思います。文字列をテキストファイルに置き換えます

私はコードを使用指定された行読むには:

fid = fopen(file_name, 'r'); 
tt = textscan(fid, '%s', 1, 'delimiter', '\n', 'headerlines', i); 
ttt = str2num(tt{1}{1}); 

file_nameは私のファイルの名前で、tttが整数に変換さi番目の文字列を含むセル配列です。例えば

ttt = 1 2 3 4 5 6 7 8

は今、私はttt = 0 0 0 0 0 0 0 0tttを変更して、ファイル内のi行目で新しいtttを書きたいと思います。

これを処理するアイデアはありますか?

答えて

0

可能な実装が

fid = fopen('input.txt', 'r+'); 
tt = textscan(fid, '%s', 1, 'delimiter', '\n', 'headerlines', 1); % scan the second line 
tt = tt{1}{1}; 
ttt = str2num(tt); %parse all the integers from the string 
ttt = ttt*0; %set all integers to zero 

fseek(fid, length(tt), 'bof'); %go back to the start of the parsed line 
format = repmat('%d ', 1, length(ttt)); 
format = format(1:end-1); %remove the trailing space 
fprintf(fid, format, ttt); %overwrite the text in the file 

fclose(fid); %close the file 

これからINPUT.TXTを変更しますです:内の既存の文字を上書きすることのみが可能であることを

your first line 
0 0 0 0 0 0 0 0 
5 5 5 5 5 5 5 5 

ノートに

your first line 
1 2 3 4 5 6 7 8 
5 5 5 5 5 5 5 5 

ファイル。新しい文字を挿入する場合は、2つの完全なファイルを書き換えるか、新しい文字を挿入する位置から少なくとも書き換えます。

関連する問題