Mini Project: Data Report
In this project you build a small but complete data pipeline: a program that writes a CSV data file, reads it back, cleans it, analyses it, plots it and writes a text report. It is the shape of countless real tasks (lab measurements, sensor logs, exports from other systems), and it uses file I/O, text parsing, logical indexing, unique/accumarray, interpolation, polyfit and functions in separate files.
The data: three temperature/humidity sensors (roof, lab, yard) reporting once a day for ten days. Like real data, the file has problems: a missing value, an error code, an impossible humidity and a duplicated row. The finished program writes a report like this one (abbreviated):
SENSOR REPORT: readings.csv
========================================
Period 2026-03-01 to 2026-03-10
...
Trend -0.50 C per dayProject layout
Each step adds one function file. In MATLAB and Octave, a function that other scripts call lives in its own .m file named after the function, in the current folder (or on the path):
| File | Job |
|---|---|
write_sample_data.m |
Creates readings.csv (stands in for the device that records the data) |
read_readings.m |
Parses the CSV into a struct of columns |
clean_readings.m |
Removes duplicates, marks bad values, fills gaps |
make_report.m |
Analyses the clean data and writes report.txt |
| your script | Calls them in order |
On this site every playground is a fresh folder, so each step repeats the files it needs (after a % --- file: line). On your computer, create each file once and keep it.
Step 1: Write the data file
fopen(name, 'w') opens a file for writing and returns a file identifier; fprintf(fid, ...) writes formatted text to it, and fclose finishes the file. Building each line with sprintf first lets the function write the duplicated row twice. Values are written as text with a fixed number of decimals, exactly as a logger would:
write_sample_data('readings.csv');
txt = fileread('readings.csv');
rows = strsplit(strtrim(txt), newline);
fprintf('%d lines written, the first six:\n', numel(rows));
fprintf(' %s\n', rows{1:6});
fprintf('the problem rows:\n');
fprintf(' %s\n', rows{[13 23 27]});
% --- file: write_sample_data.m
function write_sample_data(name)
% Writes ten days of readings from three sensors, with planted problems.
sensors = {'roof', 'lab', 'yard'};
fid = fopen(name, 'w');
fprintf(fid, 'date,sensor,temp_c,humidity\n');
for d = 1:10
for s = 1:3
temp = sprintf('%.1f', 14 + 2 * s + 3 * sin(d / 2) + 0.2 * d);
hum = sprintf('%.0f', 70 - 6 * s + 8 * cos(d / 3));
if d == 4 && s == 2, temp = ''; end % missing reading
if d == 7 && s == 3, temp = '-999'; end % sensor error code
if d == 9 && s == 1, hum = '140'; end % impossible humidity
line = sprintf('2026-03-%02d,%s,%s,%s\n', d, sensors{s}, temp, hum);
fprintf(fid, '%s', line);
if d == 2 && s == 1, fprintf(fid, '%s', line); end % duplicated row
end
end
fclose(fid);
end32 lines written, the first six:
date,sensor,temp_c,humidity
2026-03-01,roof,17.6,72
2026-03-01,lab,19.6,66
2026-03-01,yard,21.6,60
2026-03-02,roof,18.9,70
2026-03-02,roof,18.9,70
the problem rows:
2026-03-04,lab,,60
2026-03-07,yard,-999,46
2026-03-09,roof,14.9,140
Three lines show the planted problems: an empty temperature field (lab,,), the error code -999, and a humidity of 140%. The duplicated row is line 6. Using newline (a function in both MATLAB and Octave) avoids depending on how "\n" is interpreted.
Step 2: Read and parse the file
Read the file line by line with fgetl until it returns -1, split each line at the commas, and append the fields to a struct of columns. str2double converts text to numbers and returns NaN for anything that isn't a number, including the empty field, which conveniently marks it as missing.
Note:
strsplitcollapses consecutive delimiters by default, so'a,,b'would become two fields instead of three and every later column would shift. For CSV data always pass'CollapseDelimiters', false.
write_sample_data('readings.csv');
data = read_readings('readings.csv');
fprintf('%d rows read\n', numel(data.temp));
fprintf('sensors: %s\n', strjoin(unique(data.sensor), ', '));
fprintf('dates: %s to %s\n', data.date{1}, data.date{end});
fprintf('temperature: %d missing, min %g, max %g\n', sum(isnan(data.temp)), ...
min(data.temp), max(data.temp));
fprintf('humidity: %d missing, min %g, max %g\n', sum(isnan(data.humidity)), ...
min(data.humidity), max(data.humidity));
% --- file: write_sample_data.m
function write_sample_data(name)
% Writes ten days of readings from three sensors, with planted problems.
sensors = {'roof', 'lab', 'yard'};
fid = fopen(name, 'w');
fprintf(fid, 'date,sensor,temp_c,humidity\n');
for d = 1:10
for s = 1:3
temp = sprintf('%.1f', 14 + 2 * s + 3 * sin(d / 2) + 0.2 * d);
hum = sprintf('%.0f', 70 - 6 * s + 8 * cos(d / 3));
if d == 4 && s == 2, temp = ''; end % missing reading
if d == 7 && s == 3, temp = '-999'; end % sensor error code
if d == 9 && s == 1, hum = '140'; end % impossible humidity
line = sprintf('2026-03-%02d,%s,%s,%s\n', d, sensors{s}, temp, hum);
fprintf(fid, '%s', line);
if d == 2 && s == 1, fprintf(fid, '%s', line); end % duplicated row
end
end
fclose(fid);
end
% --- file: read_readings.m
function data = read_readings(name)
% Reads the CSV file into a struct of columns (one element per row).
fid = fopen(name, 'r');
if fid < 0
error('report:noFile', 'cannot open %s', name);
end
header = strsplit(fgetl(fid), ',');
data = struct('date', {{}}, 'sensor', {{}}, 'temp', [], 'humidity', [], 'raw', {{}});
line = fgetl(fid);
while ischar(line)
f = strsplit(strtrim(line), ',', 'CollapseDelimiters', false);
data.date{end + 1} = f{1};
data.sensor{end + 1} = f{2};
data.temp(end + 1) = str2double(f{3}); % '' -> NaN
data.humidity(end + 1) = str2double(f{4});
data.raw{end + 1} = line;
line = fgetl(fid);
end
fclose(fid);
end31 rows read
sensors: lab, roof, yard
dates: 2026-03-01 to 2026-03-10
temperature: 1 missing, min -999, max 23.6
humidity: 0 missing, min 44, max 140
The summary already reveals two problems: the minimum temperature is -999 and the maximum humidity is 140. Checking ranges right after reading is the quickest way to spot bad data.
In MATLAB, readtable('readings.csv') (or readmatrix for purely numeric files) does this parsing in one call. Octave doesn't have those yet; textscan(fid, '%s %s %f %f', 'Delimiter', ',', 'HeaderLines', 1) is the classic alternative in both. See CSV & Delimited Files.
Step 3: Clean the data
clean_readings applies four rules and records a note for each, because the report should say what was changed:
- Duplicates:
unique(data.raw, 'stable')returns the index of the first copy of every distinct line, in file order. - Error codes:
-999becomesNaN. - Impossible values: humidity outside 0-100% becomes
NaN. - Gaps in temperature: filled by linear interpolation between the neighbouring days of the same sensor with
interp1. Humidity gaps are left missing, and the analysis skips them.
write_sample_data('readings.csv');
data = read_readings('readings.csv');
[data, notes] = clean_readings(data);
fprintf('- %s\n', notes{:});
fprintf('%d rows left; missing: temperature %d, humidity %d\n', numel(data.temp), ...
sum(isnan(data.temp)), sum(isnan(data.humidity)));
% --- file: write_sample_data.m
function write_sample_data(name)
% Writes ten days of readings from three sensors, with planted problems.
sensors = {'roof', 'lab', 'yard'};
fid = fopen(name, 'w');
fprintf(fid, 'date,sensor,temp_c,humidity\n');
for d = 1:10
for s = 1:3
temp = sprintf('%.1f', 14 + 2 * s + 3 * sin(d / 2) + 0.2 * d);
hum = sprintf('%.0f', 70 - 6 * s + 8 * cos(d / 3));
if d == 4 && s == 2, temp = ''; end % missing reading
if d == 7 && s == 3, temp = '-999'; end % sensor error code
if d == 9 && s == 1, hum = '140'; end % impossible humidity
line = sprintf('2026-03-%02d,%s,%s,%s\n', d, sensors{s}, temp, hum);
fprintf(fid, '%s', line);
if d == 2 && s == 1, fprintf(fid, '%s', line); end % duplicated row
end
end
fclose(fid);
end
% --- file: read_readings.m
function data = read_readings(name)
% Reads the CSV file into a struct of columns (one element per row).
fid = fopen(name, 'r');
if fid < 0
error('report:noFile', 'cannot open %s', name);
end
header = strsplit(fgetl(fid), ',');
data = struct('date', {{}}, 'sensor', {{}}, 'temp', [], 'humidity', [], 'raw', {{}});
line = fgetl(fid);
while ischar(line)
f = strsplit(strtrim(line), ',', 'CollapseDelimiters', false);
data.date{end + 1} = f{1};
data.sensor{end + 1} = f{2};
data.temp(end + 1) = str2double(f{3}); % '' -> NaN
data.humidity(end + 1) = str2double(f{4});
data.raw{end + 1} = line;
line = fgetl(fid);
end
fclose(fid);
end
% --- file: clean_readings.m
function [data, notes] = clean_readings(data)
% Removes duplicates, marks bad values as NaN and fills temperature gaps.
notes = {};
[~, keep] = unique(data.raw, 'stable'); % first copy of each line
nDup = numel(data.raw) - numel(keep);
data = select_rows(data, keep);
notes{end + 1} = sprintf('removed %d duplicate row(s)', nDup);
bad = data.temp == -999;
data.temp(bad) = NaN;
notes{end + 1} = sprintf('%d temperature error code(s) -999 set to missing', nnz(bad));
bad = data.humidity < 0 | data.humidity > 100;
data.humidity(bad) = NaN;
notes{end + 1} = sprintf('%d humidity value(s) outside 0-100 set to missing', nnz(bad));
day = cellfun(@(d) str2double(d(9:10)), data.date);
names = unique(data.sensor);
for s = 1:numel(names)
rows = find(strcmp(data.sensor, names{s}));
gap = rows(isnan(data.temp(rows)));
ok = rows(~isnan(data.temp(rows)));
if ~isempty(gap)
data.temp(gap) = interp1(day(ok), data.temp(ok), day(gap));
notes{end + 1} = sprintf('%s: interpolated temperature on %s', names{s}, ...
strjoin(data.date(gap), ', '));
end
end
data.day = day;
end
function d = select_rows(d, idx)
d.date = d.date(idx); d.sensor = d.sensor(idx);
d.temp = d.temp(idx); d.humidity = d.humidity(idx); d.raw = d.raw(idx);
end- removed 1 duplicate row(s)
- 1 temperature error code(s) -999 set to missing
- 1 humidity value(s) outside 0-100 set to missing
- lab: interpolated temperature on 2026-03-04
- yard: interpolated temperature on 2026-03-07
30 rows left; missing: temperature 0, humidity 1
The helper select_rows is a local function in clean_readings.m: only that file can call it. It keeps every column in step when rows are removed, the most common source of bugs when data lives in parallel arrays.
Step 4: Analyse
With clean data, group by sensor with unique + accumarray (as in A Data Analysis Workflow), average the three sensors per day, find the extremes, and fit a straight line through all temperatures to get the trend:
write_sample_data('readings.csv');
[data, notes] = clean_readings(read_readings('readings.csv'));
[names, ~, g] = unique(data.sensor);
g = g(:);
stats.n = accumarray(g, 1);
stats.mean = accumarray(g, data.temp(:), [], @mean);
stats.min = accumarray(g, data.temp(:), [], @min);
stats.max = accumarray(g, data.temp(:), [], @max);
stats.hum = accumarray(g, data.humidity(:), [], @(h) mean(h(~isnan(h))));
fprintf('%-6s %3s %7s %6s %6s %9s\n', 'sensor', 'n', 'mean', 'min', 'max', 'humidity');
for s = 1:numel(names)
fprintf('%-6s %3d %7.2f %6.1f %6.1f %8.1f%%\n', names{s}, stats.n(s), ...
stats.mean(s), stats.min(s), stats.max(s), stats.hum(s));
end
daily = accumarray(data.day(:), data.temp(:), [], @mean); % mean of the 3 sensors
[hot, dHot] = max(daily);
[cold, dCold] = min(daily);
fprintf('warmest day: %d (%.2f C), coolest day: %d (%.2f C)\n', dHot, hot, dCold, cold);
p = polyfit(data.day, data.temp, 1);
fprintf('trend: %+.2f C per day\n', p(1));
% --- file: write_sample_data.m
function write_sample_data(name)
% Writes ten days of readings from three sensors, with planted problems.
sensors = {'roof', 'lab', 'yard'};
fid = fopen(name, 'w');
fprintf(fid, 'date,sensor,temp_c,humidity\n');
for d = 1:10
for s = 1:3
temp = sprintf('%.1f', 14 + 2 * s + 3 * sin(d / 2) + 0.2 * d);
hum = sprintf('%.0f', 70 - 6 * s + 8 * cos(d / 3));
if d == 4 && s == 2, temp = ''; end % missing reading
if d == 7 && s == 3, temp = '-999'; end % sensor error code
if d == 9 && s == 1, hum = '140'; end % impossible humidity
line = sprintf('2026-03-%02d,%s,%s,%s\n', d, sensors{s}, temp, hum);
fprintf(fid, '%s', line);
if d == 2 && s == 1, fprintf(fid, '%s', line); end % duplicated row
end
end
fclose(fid);
end
% --- file: read_readings.m
function data = read_readings(name)
% Reads the CSV file into a struct of columns (one element per row).
fid = fopen(name, 'r');
if fid < 0
error('report:noFile', 'cannot open %s', name);
end
header = strsplit(fgetl(fid), ',');
data = struct('date', {{}}, 'sensor', {{}}, 'temp', [], 'humidity', [], 'raw', {{}});
line = fgetl(fid);
while ischar(line)
f = strsplit(strtrim(line), ',', 'CollapseDelimiters', false);
data.date{end + 1} = f{1};
data.sensor{end + 1} = f{2};
data.temp(end + 1) = str2double(f{3}); % '' -> NaN
data.humidity(end + 1) = str2double(f{4});
data.raw{end + 1} = line;
line = fgetl(fid);
end
fclose(fid);
end
% --- file: clean_readings.m
function [data, notes] = clean_readings(data)
% Removes duplicates, marks bad values as NaN and fills temperature gaps.
notes = {};
[~, keep] = unique(data.raw, 'stable'); % first copy of each line
nDup = numel(data.raw) - numel(keep);
data = select_rows(data, keep);
notes{end + 1} = sprintf('removed %d duplicate row(s)', nDup);
bad = data.temp == -999;
data.temp(bad) = NaN;
notes{end + 1} = sprintf('%d temperature error code(s) -999 set to missing', nnz(bad));
bad = data.humidity < 0 | data.humidity > 100;
data.humidity(bad) = NaN;
notes{end + 1} = sprintf('%d humidity value(s) outside 0-100 set to missing', nnz(bad));
day = cellfun(@(d) str2double(d(9:10)), data.date);
names = unique(data.sensor);
for s = 1:numel(names)
rows = find(strcmp(data.sensor, names{s}));
gap = rows(isnan(data.temp(rows)));
ok = rows(~isnan(data.temp(rows)));
if ~isempty(gap)
data.temp(gap) = interp1(day(ok), data.temp(ok), day(gap));
notes{end + 1} = sprintf('%s: interpolated temperature on %s', names{s}, ...
strjoin(data.date(gap), ', '));
end
end
data.day = day;
end
function d = select_rows(d, idx)
d.date = d.date(idx); d.sensor = d.sensor(idx);
d.temp = d.temp(idx); d.humidity = d.humidity(idx); d.raw = d.raw(idx);
endsensor n mean min max humidity
lab 10 19.33 16.9 21.6 56.7%
roof 10 17.36 14.9 19.6 63.4%
yard 10 21.38 18.9 23.6 50.7%
warmest day: 3 (21.60 C), coolest day: 9 (16.90 C)
trend: -0.50 C per day
The humidity column uses an anonymous function @(h) mean(h(~isnan(h))) so that the one missing value doesn't turn the roof sensor's mean into NaN. The yard sensor is the warmest, the trend is about half a degree of cooling per day, and day 3 was the warmest.
Step 5: Plot
One line per sensor shows the cooling trend and the constant offsets between the sensors. Loop over the sensor names and plot the matching rows:
figure
hold on
for s = 1:numel(names)
rows = strcmp(data.sensor, names{s});
plot(data.day(rows), data.temp(rows), '-o', 'LineWidth', 1.5)
end
hold off
legend(names, 'Location', 'northeast')
xlabel('Day of March 2026'), ylabel('Temperature (C)')
title('Temperature by sensor'), grid on
print('-dpng', 'temperatures.png') % save it next to the reportprint('-dpng', ...) (or saveas, and exportgraphics in MATLAB) saves the figure so the report can refer to it; see Saving & Exporting Figures.
Step 6: Write the report
make_report puts everything together: it reads, cleans and analyses the input file, then writes the report with fprintf(fid, ...). The script displays the finished file with fileread. This is the complete program; all four function files are included:
write_sample_data('readings.csv');
make_report('readings.csv', 'report.txt');
disp(fileread('report.txt'))
% --- file: make_report.m
function make_report(infile, outfile)
% Reads, cleans and analyses a readings file and writes a text report.
[data, notes] = clean_readings(read_readings(infile));
[names, ~, g] = unique(data.sensor);
g = g(:);
n = accumarray(g, 1);
avg = accumarray(g, data.temp(:), [], @mean);
lo = accumarray(g, data.temp(:), [], @min);
hi = accumarray(g, data.temp(:), [], @max);
hum = accumarray(g, data.humidity(:), [], @(h) mean(h(~isnan(h))));
daily = accumarray(data.day(:), data.temp(:), [], @mean);
[hot, dHot] = max(daily);
p = polyfit(data.day, data.temp, 1);
[~, order] = sort(avg, 'descend');
fid = fopen(outfile, 'w');
fprintf(fid, 'SENSOR REPORT: %s\n', infile);
fprintf(fid, '%s\n', repmat('=', 1, 40));
fprintf(fid, 'Period %s to %s\n', data.date{1}, data.date{end});
fprintf(fid, 'Sensors %d, readings %d\n\n', numel(names), numel(data.temp));
fprintf(fid, 'Data cleaning\n');
fprintf(fid, ' - %s\n', notes{:});
fprintf(fid, '\nTemperature by sensor (warmest first)\n');
fprintf(fid, ' %-6s %3s %7s %6s %6s %9s\n', 'sensor', 'n', 'mean', 'min', 'max', 'humidity');
for s = order'
fprintf(fid, ' %-6s %3d %7.2f %6.1f %6.1f %8.1f%%\n', names{s}, n(s), avg(s), lo(s), hi(s), hum(s));
end
fprintf(fid, '\nWarmest day %s, mean %.2f C\n', data.date{find(data.day == dHot, 1)}, hot);
fprintf(fid, 'Trend %+.2f C per day\n', p(1));
fclose(fid);
end
% --- file: write_sample_data.m
function write_sample_data(name)
% Writes ten days of readings from three sensors, with planted problems.
sensors = {'roof', 'lab', 'yard'};
fid = fopen(name, 'w');
fprintf(fid, 'date,sensor,temp_c,humidity\n');
for d = 1:10
for s = 1:3
temp = sprintf('%.1f', 14 + 2 * s + 3 * sin(d / 2) + 0.2 * d);
hum = sprintf('%.0f', 70 - 6 * s + 8 * cos(d / 3));
if d == 4 && s == 2, temp = ''; end % missing reading
if d == 7 && s == 3, temp = '-999'; end % sensor error code
if d == 9 && s == 1, hum = '140'; end % impossible humidity
line = sprintf('2026-03-%02d,%s,%s,%s\n', d, sensors{s}, temp, hum);
fprintf(fid, '%s', line);
if d == 2 && s == 1, fprintf(fid, '%s', line); end % duplicated row
end
end
fclose(fid);
end
% --- file: read_readings.m
function data = read_readings(name)
% Reads the CSV file into a struct of columns (one element per row).
fid = fopen(name, 'r');
if fid < 0
error('report:noFile', 'cannot open %s', name);
end
header = strsplit(fgetl(fid), ',');
data = struct('date', {{}}, 'sensor', {{}}, 'temp', [], 'humidity', [], 'raw', {{}});
line = fgetl(fid);
while ischar(line)
f = strsplit(strtrim(line), ',', 'CollapseDelimiters', false);
data.date{end + 1} = f{1};
data.sensor{end + 1} = f{2};
data.temp(end + 1) = str2double(f{3}); % '' -> NaN
data.humidity(end + 1) = str2double(f{4});
data.raw{end + 1} = line;
line = fgetl(fid);
end
fclose(fid);
end
% --- file: clean_readings.m
function [data, notes] = clean_readings(data)
% Removes duplicates, marks bad values as NaN and fills temperature gaps.
notes = {};
[~, keep] = unique(data.raw, 'stable'); % first copy of each line
nDup = numel(data.raw) - numel(keep);
data = select_rows(data, keep);
notes{end + 1} = sprintf('removed %d duplicate row(s)', nDup);
bad = data.temp == -999;
data.temp(bad) = NaN;
notes{end + 1} = sprintf('%d temperature error code(s) -999 set to missing', nnz(bad));
bad = data.humidity < 0 | data.humidity > 100;
data.humidity(bad) = NaN;
notes{end + 1} = sprintf('%d humidity value(s) outside 0-100 set to missing', nnz(bad));
day = cellfun(@(d) str2double(d(9:10)), data.date);
names = unique(data.sensor);
for s = 1:numel(names)
rows = find(strcmp(data.sensor, names{s}));
gap = rows(isnan(data.temp(rows)));
ok = rows(~isnan(data.temp(rows)));
if ~isempty(gap)
data.temp(gap) = interp1(day(ok), data.temp(ok), day(gap));
notes{end + 1} = sprintf('%s: interpolated temperature on %s', names{s}, ...
strjoin(data.date(gap), ', '));
end
end
data.day = day;
end
function d = select_rows(d, idx)
d.date = d.date(idx); d.sensor = d.sensor(idx);
d.temp = d.temp(idx); d.humidity = d.humidity(idx); d.raw = d.raw(idx);
endSENSOR REPORT: readings.csv
========================================
Period 2026-03-01 to 2026-03-10
Sensors 3, readings 30
Data cleaning
- removed 1 duplicate row(s)
- 1 temperature error code(s) -999 set to missing
- 1 humidity value(s) outside 0-100 set to missing
- lab: interpolated temperature on 2026-03-04
- yard: interpolated temperature on 2026-03-07
Temperature by sensor (warmest first)
sensor n mean min max humidity
yard 10 21.38 18.9 23.6 50.7%
lab 10 19.33 16.9 21.6 56.7%
roof 10 17.36 14.9 19.6 63.4%
Warmest day 2026-03-03, mean 21.60 C
Trend -0.50 C per day
Writing to a file uses exactly the same format strings as printing to the screen; the only difference is the first argument fid. While developing, you can pass 1 as the file identifier: fprintf(1, ...) writes to the Command Window.
Ideas for extensions
- Make the rules configurable: pass the valid humidity range and the error code to
clean_readingsas arguments with defaults (see Flexible Arguments). - Flag readings that differ from the same day's other sensors by more than 3 degrees as suspicious.
- Add a per-sensor trend with
polyfitinside a loop, and list the sensors from fastest to slowest cooling. - Save the clean data as a new CSV file with
fprintf, or as a MAT-file withsave('-v7', 'clean.mat', 'data')(see MAT-Files: save & load). - Test
read_readingsandclean_readingswith tiny hand-made files (see Unit Testing).
Test yourself
Why does read_readings call strsplit(line, ',', 'CollapseDelimiters', false)?
- It is faster
- Without it, an empty field between two commas disappears and the columns shift
- strsplit needs it for numbers
- To remove spaces
What does str2double('') return?
- 0
- An empty array
- NaN
- An error
Which call removes repeated rows but keeps the original order of the first copies?
sort(rows)unique(rows)[~, keep] = unique(rows, 'stable')rows(end:-1:1)