A Data Analysis Workflow
Most analysis jobs follow the same path, whatever the data: get it in, look at it, clean it, reshape it, summarise it, and present the result. This lesson walks through that path from start to finish on a small sales dataset, using only core functions that work in MATLAB and Octave. At the end you'll see how the same job looks with MATLAB's table functions.
| Step | Question | Tools used here |
|---|---|---|
| 1. Import & inspect | What is in the data? How much is missing? | numel, unique, isnan, min/max |
| 2. Clean | Which values are wrong, missing or inconsistently written? | strtrim, lower/upper, isnan, median |
| 3. Transform | What new columns do I need? | element-wise maths |
| 4. Group & summarise | How do the groups compare? | unique + accumarray |
| 5. Sort & report | What should the reader see first? | sort, fprintf |
| 6. Visualise | What does it look like? | bar, plot |
The dataset
A small tea shop chain recorded 16 orders over three months. In a real project these would come from a file (see CSV & Delimited Files); here they are typed into the script as parallel arrays, one element per order. Text columns are cell arrays of char vectors, numeric columns are row vectors:
region = {'North','South','North','East','West','South','East','North', ...
'West','East','South','North','West','East','South','West'};
product = {'Tea','Coffee','coffee','Tea','Cocoa','Tea ','Coffee','Cocoa', ...
'Tea','Cocoa','Coffee','TEA','Coffee','Tea','Cocoa','Tea'};
month = [1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 3];
units = [12 30 NaN 8 15 22 -1 9 14 NaN 27 16 21 11 7 13];
price = [4.5 6.0 6.0 4.5 5.25 4.5 6.0 5.25 4.5 5.25 6.0 4.5 6.0 4.5 5.25 4.5];It contains the usual problems on purpose: two missing quantities (NaN), one impossible value (-1 units) and product names typed in different ways.
Step 1: Inspect
Before changing anything, find out what you have. Count rows, list the distinct labels, and check the numeric ranges and missing values:
region = {'North','South','North','East','West','South','East','North', ...
'West','East','South','North','West','East','South','West'};
product = {'Tea','Coffee','coffee','Tea','Cocoa','Tea ','Coffee','Cocoa', ...
'Tea','Cocoa','Coffee','TEA','Coffee','Tea','Cocoa','Tea'};
month = [1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 3];
units = [12 30 NaN 8 15 22 -1 9 14 NaN 27 16 21 11 7 13];
price = [4.5 6.0 6.0 4.5 5.25 4.5 6.0 5.25 4.5 5.25 6.0 4.5 6.0 4.5 5.25 4.5];
fprintf('%d orders over months %d-%d\n', numel(units), min(month), max(month));
fprintf('regions: %s\n', strjoin(unique(region), ', '));
fprintf('products: %s\n', strjoin(unique(product), ' | '));
fprintf('units: min %g, max %g, missing %d\n', min(units), max(units), sum(isnan(units)));
fprintf('prices: %s\n', mat2str(unique(price)));16 orders over months 1-3
regions: East, North, South, West
products: Cocoa | Coffee | TEA | Tea | Tea | coffee
units: min -1, max 30, missing 2
prices: [4.5 5.25 6]
Three findings: unique reports six "products" where there should be three (case and a trailing space), the minimum quantity is negative, and two quantities are missing. Notice that min and max skip NaN automatically, but sum and mean don't: one NaN makes the whole result NaN.
Step 2: Clean
Fix the text first, so that grouping works, then deal with the numbers. A value that cannot be true (negative units) is treated like a missing one. For the gaps there are two common choices: drop the incomplete rows, or fill them with a sensible estimate. Here each gap is filled with the median quantity of the same product, computed from the values that were known before filling:
product = {'Tea','Coffee','coffee','Tea','Cocoa','Tea ','Coffee','Cocoa', ...
'Tea','Cocoa','Coffee','TEA','Coffee','Tea','Cocoa','Tea'};
units = [12 30 NaN 8 15 22 -1 9 14 NaN 27 16 21 11 7 13];
% 1. tidy the text: trim spaces, then one spelling ("Capitalised")
product = strtrim(product);
product = cellfun(@(s) [upper(s(1)) lower(s(2:end))], product, 'UniformOutput', false);
fprintf('products: %s\n', strjoin(unique(product), ', '));
% 2. impossible values become missing
units(units < 0) = NaN;
% 3. fill each gap with the median of the same product
known = ~isnan(units);
for k = find(~known)
same = strcmp(product, product{k}) & known;
units(k) = median(units(same));
fprintf('order %2d (%s): filled with %g units\n', k, product{k}, units(k));
end
fprintf('missing values left: %d\n', sum(isnan(units)));products: Cocoa, Coffee, Tea
order 3 (Coffee): filled with 27 units
order 7 (Coffee): filled with 27 units
order 10 (Cocoa): filled with 9 units
missing values left: 0
Dropping is a one-liner with a logical mask: bad = isnan(units); units(bad) = []; region(bad) = []; and so on for every column. Whatever you choose, apply the same mask to every parallel array, or the rows go out of step. Keep a note of what you changed: cleaning decisions belong in the report.
Tip: MATLAB (not Octave) has
rmmissing,fillmissing(x, 'linear')andstandardizeMissing(x, -999)for these chores. The explicit versions above work in both and make the rule visible.
Steps 3-5: Transform, group, sort and report
Now add a derived column, revenue, and summarise it by region. The pattern [names, ~, g] = unique(labels) returns the distinct labels and, for every row, the group number g. accumarray(g, values, [], @fun) then applies fun to the values of each group (the default is a sum). See Sets & unique for more on unique.
region = {'North','South','North','East','West','South','East','North', ...
'West','East','South','North','West','East','South','West'};
product = {'Tea','Coffee','Coffee','Tea','Cocoa','Tea','Coffee','Cocoa', ...
'Tea','Cocoa','Coffee','Tea','Coffee','Tea','Cocoa','Tea'}; % cleaned
units = [12 30 27 8 15 22 27 9 14 9 27 16 21 11 7 13]; % cleaned
price = [4.5 6.0 6.0 4.5 5.25 4.5 6.0 5.25 4.5 5.25 6.0 4.5 6.0 4.5 5.25 4.5];
revenue = units .* price; % step 3: derived column
[names, ~, g] = unique(region); % step 4: group
g = g(:);
orders = accumarray(g, 1);
total = accumarray(g, revenue(:));
average = accumarray(g, revenue(:), [], @mean);
largest = accumarray(g, revenue(:), [], @max);
[~, order] = sort(total, 'descend'); % step 5: sort and report
fprintf('%-6s %6s %9s %8s %8s %6s\n', 'Region', 'Orders', 'Revenue', 'Average', 'Largest', 'Share');
for k = order'
fprintf('%-6s %6d %9.2f %8.2f %8.2f %5.1f%%\n', names{k}, orders(k), total(k), ...
average(k), largest(k), 100 * total(k) / sum(total));
end
fprintf('%-6s %6d %9.2f\n', 'All', sum(orders), sum(total));Region Orders Revenue Average Largest Share
South 4 477.75 119.44 180.00 33.3%
North 4 335.25 83.81 162.00 23.4%
West 4 326.25 81.56 126.00 22.8%
East 4 294.75 73.69 162.00 20.6%
All 16 1434.00
A fixed-width fprintf format (%-6s left-aligns text in 6 characters, %9.2f right-aligns numbers) turns the summary into a readable table. Sorting by total puts the most important row first.
Two-way summaries
accumarray also accepts two group columns, which gives a pivot table: here revenue by month (rows) and product (columns). Combinations that never occur are filled with 0:
product = {'Tea','Coffee','Coffee','Tea','Cocoa','Tea','Coffee','Cocoa', ...
'Tea','Cocoa','Coffee','Tea','Coffee','Tea','Cocoa','Tea'};
month = [1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 3];
units = [12 30 27 8 15 22 27 9 14 9 27 16 21 11 7 13];
price = [4.5 6.0 6.0 4.5 5.25 4.5 6.0 5.25 4.5 5.25 6.0 4.5 6.0 4.5 5.25 4.5];
revenue = units .* price;
[pnames, ~, p] = unique(product);
pivot = accumarray([month(:) p(:)], revenue(:));
fprintf('%-6s', 'Month'); fprintf('%9s', pnames{:}); fprintf('%9s\n', 'Total');
for m = 1:size(pivot, 1)
fprintf('%-6d', m); fprintf('%9.2f', pivot(m, :)); fprintf('%9.2f\n', sum(pivot(m, :)));
end
[~, bestMonth] = max(sum(pivot, 2));
[~, bestProduct] = max(sum(pivot, 1));
fprintf('best month: %d, best product: %s\n', bestMonth, pnames{bestProduct});Month Cocoa Coffee Tea Total
1 78.75 342.00 90.00 510.75
2 94.50 162.00 162.00 418.50
3 36.75 288.00 180.00 504.75
best month: 1, best product: Coffee
Step 6: Visualise
A grouped bar chart of the pivot table shows the month-by-product pattern at a glance. bar with a matrix draws one group per row and one colour per column:
bar(pivot)
set(gca, 'XTickLabel', {'Jan', 'Feb', 'Mar'})
legend(pnames, 'Location', 'northeast')
ylabel('Revenue'); title('Revenue by month and product')Coffee dominates January and March, while February is evenly split between coffee and tea.
The same job with MATLAB tables
In MATLAB, a table keeps the columns together, so cleaning one row cleans it everywhere, and grouping functions do the bookkeeping. Octave doesn't support table yet, which is why the steps above use parallel arrays. See Tables for the details.
T = table(string(region'), string(product'), month', units', price', ...
'VariableNames', {'Region', 'Product', 'Month', 'Units', 'Price'});
T.Product = strip(T.Product); % clean the text
T.Units(T.Units < 0) = NaN;
T = rmmissing(T); % or fillmissing
T.Revenue = T.Units .* T.Price;
S = groupsummary(T, 'Region', {'sum', 'mean'}, 'Revenue');
S = sortrows(S, 'sum_Revenue', 'descend')MATLAB output (this version drops the three incomplete orders instead of filling them):
S =
4×4 table
Region GroupCount sum_Revenue mean_Revenue
_______ __________ ___________ ____________
"South" 4 477.75 119.44
"West" 4 326.25 81.562
"North" 3 173.25 57.75
"East" 2 85.5 42.75 Other table tools worth knowing: groupcounts, pivot (R2023a), unstack, varfun and rowfun. The ideas, group numbers and per-group functions, are exactly the ones you used with unique and accumarray.
Learn more: Statistics Functions, Bar, Histogram, Pie & Scatter, and the end-to-end Mini Project: Data Report. The same workflow in Python is covered in pandas.
Test yourself
Given [names, ~, g] = unique(region), what does accumarray(g(:), revenue(:)) return?
- The revenue sorted by region
- The total revenue for each distinct region, in the order of
names - The number of orders per region
- The largest revenue overall
Why does unique report six products in the raw data?
- unique is case-insensitive
- Different spellings ('coffee', 'TEA', 'Tea ') count as different labels
- There really are six products
- NaN values create extra groups
Which statement about missing values is true?
- sum and mean ignore NaN automatically
- min and max skip NaN, but sum and mean return NaN if any element is NaN
- NaN == NaN is true
- isnan only works on matrices