An electrodermal-activity pipeline: raw skin conductance in, one composite arousal index out. Impulse rejection, zero-phase filtering, response detection and ten extracted features, with every input validated.
×1.97composite index under fear against baseline, on the recorded sessions
48 Hzsampling rate, Grove GSR sensor through an Arduino ADC
10extracted features
8source files, all on this page
One record, five stages.
Two conditions, a baseline and a fear stimulus, pass through the same chain. The scope below runs a line-for-line port of the MATLAB source in your browser. The recordings themselves are not public, so the traces here are synthetic. The measured result follows.
BaselineFearRaw, µS
Responses
Largest response
Variance
Composite index
Baseline
0
0
0
0
Fear
0
0
0
0
Synthetic recordings: a slow tonic level, discrete responses, sensor noise and occasional contact spikes, generated on this page. The numbers are computed from them by the same steps as the source and describe these traces only.
Measured on the recorded sessions.
Two sessions of about 130 seconds each, a baseline and a fear stimulus, recorded at 48 Hz with a Grove GSR sensor through an Arduino ADC. The composite index reads 127,064 at baseline and 249,791 under fear.
BaselineFear
F1Mean level73.5857.89
F2Variance1,082.3645.7
F3Total rise time, ms97,82386,167
F4Total response amplitude198.2350.1
F5Response area18,403156,080
F6Largest response48.3526.99
F7Rise time of the largest response, ms1191,978
F8Response count1,657798
F9RMS level80.6063.22
F10Mobility-style frequency0.00120.00085
Composite index127,064249,791
Three terms carry the separation. Response area is 8.5 times larger under fear, total response amplitude rises from 198 to 350, and the largest response takes 1,978 ms to peak against 119. Level, variance and the raw peak count run the other way: with no prominence floor, the flatter baseline registers more ripple peaks.
The recorded sessions before and after impulse rejection. Contact spikes of several hundred µS ride on a signal near 150 µS; the three-point median removes them and leaves the response shape intact. MATLAB output, December 2023, recoloured for this page.
The chain, with its source.
Seven functions, each doing one job, each validating its input. The listings are the published files.
01Ingest
Timestamp parsing with row-level validation.
Readings arrive as text, stamped mm:ss:ms. The loader converts each stamp to milliseconds, rejects malformed or non-numeric rows by row number, and returns two aligned column vectors.
Input
CSV, one header row
Time base
milliseconds
On bad data
fails with the row number
Show loadAndProcessCSV.mloadAndProcessCSV.mRawGitHub
function [timeMillis, values] = loadAndProcessCSV(filename)
validateattributes(filename, {'char', 'string'}, {'scalartext'}, mfilename, 'filename');
if ~isfile(filename)
error('Input CSV file not found: %s', filename);
end
data = readtable(filename, 'ReadVariableNames', false, 'HeaderLines', 1, 'Format', '%s%s');
timeMillis = zeros(height(data), 1);
values = zeros(height(data), 1);
for idx = 1:height(data)
timeParts = split(string(data.Var1{idx}), ':');
if numel(timeParts) ~= 3
error('Invalid timestamp format on row %d. Expected mm:ss:ms.', idx + 1);
end
minutes = str2double(timeParts{1});
seconds = str2double(timeParts{2});
millis = str2double(timeParts{3});
sampleValue = str2double(data.Var2{idx});
if any(isnan([minutes, seconds, millis, sampleValue]))
error('Encountered non-numeric data on row %d.', idx + 1);
end
timeMillis(idx) = (minutes * 60 + seconds) * 1000 + millis;
values(idx) = sampleValue;
endend
02Impulse rejection
A recursive three-point median.
Contact artefacts show up as single-sample spikes. A running median over three samples removes them without the edge smearing a linear filter would add; each output feeds the next window, which makes the filter recursive.
Window
3 samples
Form
recursive, in place
Edges
first and last sample held
Show applyThirdOrderMedianFilter.mapplyThirdOrderMedianFilter.mRawGitHub
Second-order Butterworth, run forward and backward.
A maximally flat passband at 48 Hz sampling with a 20 Hz corner. Running the filter in both directions cancels its phase response and squares its magnitude response, so peaks keep their timing through filtering.
Design
Butterworth, order 2
Corner
20 Hz at 48 Hz, 0.83 of Nyquist
Application
filtfilt, zero phase
Show applyLowPassFilter.mapplyLowPassFilter.mRawGitHub
A boxcar FIR over the trailing ten samples, about 208 ms. The window grows from one sample at the start of the record, so the output has no start-up gap and uses no future data.
Window
10 samples, about 208 ms
Form
causal boxcar FIR
Start-up
growing window
Show applyMovingAverageFilter.mapplyMovingAverageFilter.mRawGitHub
Absolute conductance differs from person to person and session to session. Rescaling each record to 0 to 100 puts the two conditions on one axis, so they are compared on shape. A flat record returns zeros instead of dividing by zero.
function normalizedData = normalizeGSR(data)
validateattributes(data, {'numeric'}, {'vector', 'nonempty', 'finite'}, mfilename, 'data');
data = data(:);
minVal = min(data);
maxVal = max(data);
rangeVal = maxVal - minVal;
if rangeVal == 0
normalizedData = zeros(size(data));
return;
end
normalizedData = 100 * (data - minVal) / rangeVal;
end
06Feature extraction
Ten features over the skin-conductance responses.
Peaks are located with findpeaks. For each, the onset is the last sample before the peak where the first difference turns negative, which yields an amplitude and a rise time per response. Level, dispersion, energy and a mobility-style frequency term complete the set.
Responses
peak and onset per event
No peaks found
amplitude terms set to zero
Zero energy
frequency term set to zero
Show calculateGSRFeatures.mcalculateGSRFeatures.mRawGitHub
function features = calculateGSRFeatures(gsr_values, time_values)
validateattributes(gsr_values, {'numeric'}, {'vector', 'nonempty', 'finite'}, mfilename, 'gsr_values');
validateattributes(time_values, {'numeric'}, {'vector', 'nonempty', 'finite'}, mfilename, 'time_values');
gsr_values = gsr_values(:);
time_values = time_values(:);
if numel(gsr_values) ~= numel(time_values)
error('Signal and time vectors must have the same number of elements.');
end
features = struct();
features.F1 = mean(gsr_values);
features.F2 = var(gsr_values);
[scrAmplitudes, scrRiseTimes] = identifySCRs(gsr_values, time_values);
features.F3 = sum(scrRiseTimes);
features.F4 = sum(scrAmplitudes);
features.F5 = sum(0.5 .* scrAmplitudes .* scrRiseTimes);
features.F8 = numel(scrAmplitudes);
features.F9 = sqrt(mean(gsr_values .^ 2));
if isempty(scrAmplitudes)
features.F6 = 0;
features.F7 = 0;
else
[features.F6, maxAmpIndex] = max(scrAmplitudes);
features.F7 = scrRiseTimes(maxAmpIndex);
end
deltaGSR = diff(gsr_values);
signalEnergy = sum(gsr_values .^ 2);
if signalEnergy == 0
features.F10 = 0;
else
features.F10 = (1 / (2 * pi)) * sqrt(sum(deltaGSR .^ 2) / signalEnergy);
endendfunction [scrAmplitudes, scrRiseTimes] = identifySCRs(gsr_values, time_values)
[~, peakLocations] = findpeaks(gsr_values);
scrAmplitudes = zeros(1, numel(peakLocations));
scrRiseTimes = zeros(1, numel(peakLocations));
for idx = 1:numel(peakLocations)
peakLocation = peakLocations(idx);
onsetLocation = find(diff(gsr_values(1:peakLocation)) < 0, 1, 'last');
if isempty(onsetLocation)
onsetLocation = 1;
end
scrAmplitudes(idx) = gsr_values(peakLocation) - gsr_values(onsetLocation);
scrRiseTimes(idx) = time_values(peakLocation) - time_values(onsetLocation);
endend
07Composite index
A fixed-weight linear composite.
The ten features collapse into one scalar. The response count carries the largest weight and the RMS level the smallest. The function refuses to run if any feature is missing.
Form
weighted sum of F1 to F10
Largest weight
5, on response count
Guard
all ten fields required
Show calculateFearIndex.mcalculateFearIndex.mRawGitHub
Computed on the normalised record x, with A the amplitude and tᵣ the rise time of each detected response. The last column is the weight in the composite index.
One script runs both conditions through the chain, prints the features and the index for each, and plots every stage side by side. Data files resolve from the project root or a data folder, with a clear error if neither holds them.
% ASSIGNMENT 4: Electrical/Bioengineering Case Study - Fear Analysis using GSR data% Author: Mahfuz% Date Created: December 19, 2023%% This script analyzes galvanic skin response (GSR) data collected in% baseline and fear conditions. It applies a signal-processing pipeline,% extracts features, computes a weighted fear index, and visualizes each% stage of the workflow.
clc;
clearvars;
close all;
projectRoot = fileparts(mfilename('fullpath'));
conditionConfigs = [
struct('name', 'Baseline', 'filename', 'GSR_Baseline.csv', 'color', 'b')
struct('name', 'Fear', 'filename', 'GSR_FEAR.csv', 'color', 'r')
];
results = repmat(struct( ...
'name', '', ...
'color', '', ...
'timeMillis', [], ...
'raw', [], ...
'medianFiltered', [], ...
'lowPassFiltered', [], ...
'movingAverageFiltered', [], ...
'normalized', [], ...
'features', struct(), ...
'fearIndex', 0), size(conditionConfigs));
for idx = 1:numel(conditionConfigs)
results(idx) = runConditionAnalysis(projectRoot, conditionConfigs(idx));
printConditionSummary(results(idx));
end
plotProcessingStages(results);
function result = runConditionAnalysis(projectRoot, config)
dataFile = resolveDataFile(projectRoot, config.filename);
[timeMillis, rawValues] = loadAndProcessCSV(dataFile);
medianFiltered = applyThirdOrderMedianFilter(rawValues);
lowPassFiltered = applyLowPassFilter(medianFiltered);
movingAverageFiltered = applyMovingAverageFilter(lowPassFiltered, 10);
normalizedSignal = normalizeGSR(movingAverageFiltered);
features = calculateGSRFeatures(normalizedSignal, timeMillis);
fearIndex = calculateFearIndex(features);
result = struct( ...
'name', config.name, ...
'color', config.color, ...
'timeMillis', timeMillis, ...
'raw', rawValues, ...
'medianFiltered', medianFiltered, ...
'lowPassFiltered', lowPassFiltered, ...
'movingAverageFiltered', movingAverageFiltered, ...
'normalized', normalizedSignal, ...
'features', features, ...
'fearIndex', fearIndex);
endfunction printConditionSummary(result)
fprintf('%s Features:\n', result.name);
disp(result.features);
fprintf('%s Fear Index: %.4f\n\n', result.name, result.fearIndex);
endfunction plotProcessingStages(results)
stageDefinitions = {
'Original Data', 'raw', 'GSR (uS)', 1'3rd Order Median Filter', 'medianFiltered', 'GSR (uS)', 2'Low Pass Filter', 'lowPassFiltered', 'GSR (uS)', 3'N-Point Moving Average', 'movingAverageFiltered', 'GSR (uS)', 4'Normalized Data', 'normalized', 'Normalized GSR', 5
};
for stageIdx = 1:size(stageDefinitions, 1) - 1
figure(stageDefinitions{stageIdx, 4});
for conditionIdx = 1:numel(results)
subplot(2, 2, conditionIdx);
plotSignal(results(conditionIdx), stageDefinitions{stageIdx, 2}, ...
stageDefinitions{stageIdx, 1}, stageDefinitions{stageIdx, 3});
subplot(2, 2, conditionIdx + 2);
plotSignal(results(conditionIdx), stageDefinitions{stageIdx + 1, 2}, ...
stageDefinitions{stageIdx + 1, 1}, stageDefinitions{stageIdx + 1, 3});
endend
figure(stageDefinitions{end, 4});
for conditionIdx = 1:numel(results)
subplot(1, numel(results), conditionIdx);
plotSignal(results(conditionIdx), stageDefinitions{end, 2}, ...
stageDefinitions{end, 1}, stageDefinitions{end, 3});
legend(results(conditionIdx).name, 'Location', 'best');
endendfunction plotSignal(result, fieldName, stageName, yLabelText)
plot(result.timeMillis, result.(fieldName), result.color, 'LineWidth', 1.25);
title(sprintf('%s: %s', result.name, stageName));
xlabel('Time (ms)');
ylabel(yLabelText);
grid on;
endfunction resolvedPath = resolveDataFile(projectRoot, filename)
candidatePaths = {
fullfile(projectRoot, filename)
fullfile(projectRoot, 'data', filename)
};
for idx = 1:numel(candidatePaths)
if isfile(candidatePaths{idx})
resolvedPath = candidatePaths{idx};
return;
endend
error(['Required data file not found: ', filename, ...
'. Place it in the project root or in a data/ directory.']);
end
Built to fail loudly, and only when it should.
Validation
Every function checks type, shape and finiteness with validateattributes before it touches the data.
Degenerate input
A flat record normalises to zeros. A record with no peaks yields zero amplitude terms. Zero signal energy yields a zero frequency term. None of them divides by zero.
Malformed rows
A bad timestamp or a non-numeric reading stops the load and names the row.
Orientation
Inputs are coerced to column vectors, so row and column data behave the same.
Next
Response detection runs without a prominence floor, so residual ripple registers as responses, and the 20 Hz corner sits high for a signal whose content lies below a few hertz. A prominence threshold and a lower corner are the first refinements.
Scope
Sole author. Written for Computer Programming for Engineers at NYU Abu Dhabi, December 2023; restructured and documented for release in April 2026.