MATLAB Mini Project
In this project you'll build a small weather station report, one step at a time. It brings together much of the course: structures, logical indexing, NaN handling, interpolation, statistics, local functions, switch, unique, polyfit and formatted output, plus a figure.
The station recorded two weeks of daily readings. Some temperature readings failed and were stored as the error code -999. By the end, your script prints a report like this (abbreviated):
=== Weather report: Hilltop, days 1-14 ===
Temperature mean 18.5 min 14.2 max 23.1
...
Warming trend: +0.43 degrees per dayEvery step is a complete script you can run (on this site, the saved Octave output is shown). Each step repeats the data so it stands on its own; in a real project you'd keep one growing script.
Step 1: Store the data in a structure
A structure keeps the related vectors together under meaningful names. One field per measured quantity, one element per day:
station.name = 'Hilltop';
station.day = 1:14;
station.temp = [14.2 15.1 -999 17.8 19.4 21.0 20.3 18.7 -999 16.2 17.5 19.9 22.4 23.1]; % deg C
station.rain = [0 2.4 4.1 0 0 0 1.2 8.6 12.3 3.4 0 0 0 0.6]; % mm
station.wind = [12 18 25 9 7 11 14 31 28 19 10 8 6 13]; % km/h
fprintf('Station %s: %d days of data\n', station.name, numel(station.day));
fprintf('Fields: %s\n', strjoin(fieldnames(station)', ', '));
fprintf('Day %d: %.1f C, %.1f mm, %d km/h\n', ...
[station.day(1:3); station.temp(1:3); station.rain(1:3); station.wind(1:3)]);Station Hilltop: 14 days of data
Fields: name, day, temp, rain, wind
Day 1: 14.2 C, 0.0 mm, 12 km/h
Day 2: 15.1 C, 2.4 mm, 18 km/h
Day 3: -999.0 C, 4.1 mm, 25 km/h
The stacked matrix in the last fprintf has one column per day, so the format is reused three times. Day 3 already shows the problem we fix next: the -999 error code.
Step 2: Clean the missing values
First mark the error codes as NaN, so no calculation can accidentally use -999. Then fill the gaps by linear interpolation between the neighbouring valid days:
day = 1:14;
temp = [14.2 15.1 -999 17.8 19.4 21.0 20.3 18.7 -999 16.2 17.5 19.9 22.4 23.1];
temp(temp == -999) = NaN;
missing = isnan(temp);
fprintf('%d missing readings on days %s\n', sum(missing), mat2str(day(missing)));
ok = ~missing;
filled = temp;
filled(missing) = interp1(day(ok), temp(ok), day(missing));
fprintf('Day %d filled with %.2f C\n', [day(missing); filled(missing)]);2 missing readings on days [3 9]
Day 3 filled with 16.45 C
Day 9 filled with 17.45 C
Interpolation is reasonable here because temperature changes smoothly from day to day. For rain, which can jump from 0 to 12 mm, you would rather leave gaps as NaN and use 'omitnan'.
Step 3: A statistics helper
A local function returns a struct of summary values. Returning one struct instead of four separate outputs keeps the calling code tidy and makes it easy to add more statistics later:
temp = [14.2 15.1 16.45 17.8 19.4 21.0 20.3 18.7 17.45 16.2 17.5 19.9 22.4 23.1];
rain = [0 2.4 4.1 0 0 0 1.2 8.6 12.3 3.4 0 0 0 0.6];
wind = [12 18 25 9 7 11 14 31 28 19 10 8 6 13];
print_stats('Temperature', summarise(temp));
print_stats('Rain', summarise(rain));
print_stats('Wind', summarise(wind));
function s = summarise(x)
s.mean = mean(x);
s.min = min(x);
s.max = max(x);
s.std = std(x);
end
function print_stats(label, s)
fprintf('%-12s mean %5.1f min %5.1f max %5.1f std %4.1f\n', ...
label, s.mean, s.min, s.max, s.std);
endTemperature mean 18.5 min 14.2 max 23.1 std 2.6
Rain mean 2.3 min 0.0 max 12.3 std 3.8
Wind mean 15.1 min 6.0 max 31.0 std 8.0
Step 4: Classify each day
Each day gets one label. The rules are checked in priority order with if/elseif, and a switch turns the label into an icon-like code for the report:
temp = [14.2 15.1 16.45 17.8 19.4 21.0 20.3 18.7 17.45 16.2 17.5 19.9 22.4 23.1];
rain = [0 2.4 4.1 0 0 0 1.2 8.6 12.3 3.4 0 0 0 0.6];
wind = [12 18 25 9 7 11 14 31 28 19 10 8 6 13];
labels = cell(1, numel(temp));
for d = 1:numel(temp)
labels{d} = classify_day(temp(d), rain(d), wind(d));
end
fprintf('%s\n', strjoin(cellfun(@short_code, labels, 'UniformOutput', false), ' '));
[kinds, ~, idx] = unique(labels);
counts = accumarray(idx(:), 1);
for k = 1:numel(kinds)
fprintf('%-6s %d days\n', kinds{k}, counts(k));
end
function label = classify_day(t, r, w)
if r >= 5
label = 'rainy';
elseif w >= 25
label = 'windy';
elseif t >= 21
label = 'warm';
else
label = 'mild';
end
end
function c = short_code(label)
switch label
case 'rainy'
c = 'R';
case 'windy'
c = 'W';
case 'warm'
c = 'H';
otherwise
c = '.';
end
end. . W . . H . R R . . . H H
mild 8 days
rainy 2 days
warm 3 days
windy 1 days
The counting loop calls fprintf once per category because kinds is a cell array of text while counts is numeric, so they can't be stacked into one matrix for a single call. unique sorts the labels alphabetically.
Step 5: Weekly summary and trend
Reshaping the 14 days into a 7-by-2 matrix puts each week in a column, so column-wise functions give weekly results directly. polyfit with degree 1 measures the warming trend:
day = 1:14;
temp = [14.2 15.1 16.45 17.8 19.4 21.0 20.3 18.7 17.45 16.2 17.5 19.9 22.4 23.1];
rain = [0 2.4 4.1 0 0 0 1.2 8.6 12.3 3.4 0 0 0 0.6];
weeklyTemp = mean(reshape(temp, 7, 2));
weeklyRain = sum(reshape(rain, 7, 2));
fprintf('Week %d: mean %.2f C, rain %.1f mm\n', [1:2; weeklyTemp; weeklyRain]);
p = polyfit(day, temp, 1);
fprintf('Warming trend: %+.2f degrees per day\n', p(1));
fprintf('Trend forecast for day 15: %.1f C\n', polyval(p, 15));Week 1: mean 17.75 C, rain 7.7 mm
Week 2: mean 19.32 C, rain 24.9 mm
Warming trend: +0.43 degrees per day
Trend forecast for day 15: 21.8 C
Step 6: Plot the temperatures
The figure shows the daily temperatures as a line with markers, the two interpolated days highlighted, and the trend line. Run this in MATLAB or Octave desktop:
day = 1:14;
temp = [14.2 15.1 16.45 17.8 19.4 21.0 20.3 18.7 17.45 16.2 17.5 19.9 22.4 23.1];
filledDays = [3 9];
p = polyfit(day, temp, 1);
plot(day, temp, '-o', 'LineWidth', 1.5)
hold on
plot(filledDays, temp(filledDays), 'rs', 'MarkerSize', 10)
plot(day, polyval(p, day), 'k--')
hold off
grid on
xlabel('Day'); ylabel('Temperature (C)')
title('Hilltop station')
legend('daily', 'interpolated', 'trend', 'Location', 'northwest')The runnable part checks the trend line's end points, and the sketch below shows the figure:
day = 1:14;
temp = [14.2 15.1 16.45 17.8 19.4 21.0 20.3 18.7 17.45 16.2 17.5 19.9 22.4 23.1];
p = polyfit(day, temp, 1);
fprintf('trend line from %.2f (day 1) to %.2f (day 14)\n', polyval(p, 1), polyval(p, 14));trend line from 15.73 (day 1) to 21.35 (day 14)
Step 7: The complete report
Finally, everything in one script: raw data in, cleaned data and a formatted report out. The main code at the top reads like a table of contents, and the details live in local functions at the end:
station.name = 'Hilltop';
station.day = 1:14;
station.temp = [14.2 15.1 -999 17.8 19.4 21.0 20.3 18.7 -999 16.2 17.5 19.9 22.4 23.1];
station.rain = [0 2.4 4.1 0 0 0 1.2 8.6 12.3 3.4 0 0 0 0.6];
station.wind = [12 18 25 9 7 11 14 31 28 19 10 8 6 13];
[station, nFilled] = clean_temperatures(station);
report(station, nFilled);
function [st, n] = clean_temperatures(st)
bad = st.temp == -999;
n = sum(bad);
st.temp(bad) = interp1(st.day(~bad), st.temp(~bad), st.day(bad));
end
function report(st, nFilled)
fprintf('=== Weather report: %s, days %d-%d ===\n', st.name, st.day(1), st.day(end));
fprintf('Temperature mean %.1f min %.1f max %.1f\n', mean(st.temp), min(st.temp), max(st.temp));
fprintf('Rain total %.1f mm on %d days\n', sum(st.rain), nnz(st.rain));
[w, d] = max(st.wind);
fprintf('Wind strongest %d km/h on day %d\n', w, d);
p = polyfit(st.day, st.temp, 1);
fprintf('Warming trend: %+.2f degrees per day\n', p(1));
fprintf('(%d temperature readings were interpolated)\n', nFilled);
end=== Weather report: Hilltop, days 1-14 ===
Temperature mean 18.5 min 14.2 max 23.1
Rain total 32.6 mm on 7 days
Wind strongest 31 km/h on day 8
Warming trend: +0.43 degrees per day
(2 temperature readings were interpolated)
Ideas to extend the project
- Add a
humidityfield and include it in the statistics with the samesummarisehelper. - Let
classify_daytake a struct of thresholds as a second input, with defaults when it's omitted (nargin). - Detect "heat waves": three or more consecutive days at 21 °C or warmer (hint:
diffof a logical mask finds starts and ends of runs). - Plot rain as bars and temperature as a line in two subplots (
subplot(2, 1, k)). - Store several stations in a struct array and print one report per station with
arrayfun.
Test yourself
Why replace the error code -999 with NaN before computing statistics?
- NaN takes less memory
- So no calculation silently uses -999 as a real temperature
- interp1 requires NaN
- fprintf cannot print -999
What does mean(reshape(temp, 7, 2)) compute for 14 daily values?
- The mean of each day
- The mean of each week (one value per column)
- The overall mean twice
- An error
In the final script, where must the local functions be placed for MATLAB?
- Before the main code
- At the end of the file
- In a separate folder
- Anywhere