processing a file but keeping blank lines intact
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Christina Verhagen
am 27 Sep. 2023
Kommentiert: Voss
am 29 Sep. 2023
Hello,
I have a script that takes a file which contains 2 columns of data (in scientific notation), then subtracts a constant value from the first column, in order to commensate for a glitch in our machine which makes the measuremetns. A new file is then produced with the new values.
However, the original file contains blank lines throughout the sequence, and the new file does not.
How do I add a line into the script that tells it to keep blank lines?
Is this possible?
Thank you!
4 Kommentare
Walter Roberson
am 29 Sep. 2023
Please post code rather than pictures of code. We cannot execute pictures of code.
Voss
am 29 Sep. 2023
@Christina Verhagen: I've modified my answer to work with your example file, please try to run it and see if it does what you want.
Akzeptierte Antwort
Voss
am 27 Sep. 2023
Bearbeitet: Voss
am 29 Sep. 2023
Here's one way:
input_file = 'file.txt';
output_file = 'file_modified.txt';
constant_offset = 100;
input_format = "%f,%f"; % modify this to match your file's format for reading
output_format = '%+.6E,%+.6E'; % modify this to try to match your file's format for writing
type(input_file); % show the original file's contents
L = readlines(input_file);
has_numbers = false(numel(L),1);
M = zeros(0,2);
for ii = 1:numel(L)
vals = textscan(L(ii),input_format);
vals = [vals{:}];
if numel(vals) == 2
has_numbers(ii) = true;
M(end+1,:) = vals;
end
end
M(:,1) = M(:,1)-constant_offset;
L(has_numbers) = compose(output_format,M);
writelines(L,output_file);
type(output_file); % show the modified file's contents
2 Kommentare
Weitere Antworten (1)
Walter Roberson
am 27 Sep. 2023
Bearbeitet: Walter Roberson
am 27 Sep. 2023
ConstantOffset = as appropriate;
filename_in = 'as appropriate';
filename_out = 'as appropriate preferably not the same';
C = readcell(filename_in);
mask = cellfun(@(V) isnumeric(V) && ~isempty(V), C(:,1));
C(mask) = cellfun(@(V)V-constant_offset, C(mask,1), 'uniform', 0);
writecell(C, filename_out);
Siehe auch
Kategorien
Mehr zu Data Type Identification finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!