我有一个包含
的test.txt文件bla bla bla
ble ble
BEGIN_SCAN
100 150
200 300
150 800
END_SCAN
blebleble
blublublu
我想更改此矩阵的BEGIN_SCAN
和END_SCAN
之间的数字
M = [100 125;
200 350;
150 835]
将结果保存在result.txt
文件中。
有什么想法吗?
答案 0 :(得分:2)
您可以使用fseek移动到文件中的特定位置(当然首先必须找到它),然后使用fprintf覆盖该行上的内容。
例如,在函数eps_remove_background
的{{3}}中使用此功能从文件中删除一行。
答案 1 :(得分:1)
这应该这样做:
txt = fileread('test.txt');
rows = regexp(txt,'\n','split');
[Lia, irows_begin] = ismember('BEGIN_SCAN', rows);
[Lia, irows_end] = ismember('END_SCAN', rows);
M_before = rows(irows_begin+1:irows_end-1);
M_before = cellfun(@(x) cell2mat(cellfun(@(y) str2num(y), strsplit(x, ' '), 'un', 0)), M_before, 'un', 0);
M_before = cell2mat(M_before(:));
M = [M_before(:,1) [125;350;835]];
M = num2cell(M, 2);
M = cellfun(@num2str, M, 'un', 0)';
rows = [rows(1:irows_begin) M rows(irows_end:end)];
fid = fopen('result.txt','wt');
fprintf(fid, '%s\n', rows{:});
fclose(fid);
答案 2 :(得分:0)
改编自@ Will的正确工作答案:
fid=fopen('test.txt');
txt =textscan(fid,'%s','delimiter','\n');
rows = txt{1,1};
irows_begin = find(ismember(rows,'BEGIN_SCAN'));
irows_end = find(ismember(rows,'END_SCAN'));
fclose(fid)
M_before = rows(irows_begin+1:irows_end-1);
M_before=cellfun(@str2num,M_before,'UniformOutput',false);
M_before = cell2mat(M_before(:));
M = [M_before(:,1) [125;350;835]];
M = num2cell(M, 2);
M = cellfun(@num2str, M, 'un', 0);
rows = [rows(1:irows_begin); M; rows(irows_end:end)];
fid = fopen('result.txt','wt');
fprintf(fid, '%s\n', rows{:});
fclose(fid);