Shihan Mahfuz

Biosignal processing, MATLAB

Skin Signal

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.

Read the source Repository

  • ×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

ResponsesLargest responseVarianceComposite index
Baseline0000
Fear0000

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.

  1. BaselineFear
  2. F1Mean level73.5857.89
  3. F2Variance1,082.3645.7
  4. F3Total rise time, ms97,82386,167
  5. F4Total response amplitude198.2350.1
  6. F5Response area18,403156,080
  7. F6Largest response48.3526.99
  8. F7Rise time of the largest response, ms1191,978
  9. F8Response count1,657798
  10. F9RMS level80.6063.22
  11. F10Mobility-style frequency0.00120.00085
  12. 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.

Four plots of the recorded sessions: raw baseline and fear signals with spikes of several hundred microsiemens, and the same signals after the median filter with the spikes removed
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.m
loadAndProcessCSV.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;
    end
end

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.m
applyThirdOrderMedianFilter.mRawGitHub
function filteredData = applyThirdOrderMedianFilter(values)
    validateattributes(values, {'numeric'}, {'vector', 'nonempty', 'finite'}, mfilename, 'values');

    filteredData = values(:);
    sampleCount = numel(filteredData);

    if sampleCount < 3
        return;
    end

    for idx = 2:sampleCount - 1
        window = filteredData(idx - 1:idx + 1);
        filteredData(idx) = median(window);
    end
end

03Zero-phase low-pass

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.m
applyLowPassFilter.mRawGitHub
function filteredData = applyLowPassFilter(data)
    validateattributes(data, {'numeric'}, {'vector', 'nonempty', 'finite'}, mfilename, 'data');

    samplingFrequencyHz = 48;
    cutoffFrequencyHz = 20;
    normalizedCutoff = cutoffFrequencyHz / (samplingFrequencyHz / 2);

    [b, a] = butter(2, normalizedCutoff);
    filteredData = filtfilt(b, a, data(:));
end

04Smoothing

A causal ten-point moving average.

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.m
applyMovingAverageFilter.mRawGitHub
function filteredData = applyMovingAverageFilter(data, N)
    validateattributes(data, {'numeric'}, {'vector', 'nonempty', 'finite'}, mfilename, 'data');
    validateattributes(N, {'numeric'}, {'scalar', 'integer', 'positive'}, mfilename, 'N');

    data = data(:);
    filteredData = zeros(size(data));
    dataSize = numel(data);

    for idx = 1:dataSize
        windowStart = max(1, idx - N + 1);
        window = data(windowStart:idx);
        filteredData(idx) = mean(window);
    end
end

05Normalisation

Min-max scaling to a common range.

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.

Range
0 to 100
Flat signal
returns zeros
Show normalizeGSR.m
normalizeGSR.mRawGitHub
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.m
calculateGSRFeatures.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);
    end
end

function [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);
    end
end

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.m
calculateFearIndex.mRawGitHub
function FearIndex = calculateFearIndex(feature)
    requiredFields = {'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10'};

    for idx = 1:numel(requiredFields)
        if ~isfield(feature, requiredFields{idx})
            error('Missing required feature field: %s', requiredFields{idx});
        end
    end

    FearIndex = feature.F1 + ...
        2 * feature.F2 + ...
        feature.F3 + ...
        0.5 * feature.F4 + ...
        feature.F5 + ...
        2 * feature.F6 + ...
        feature.F7 + ...
        5 * feature.F8 + ...
        0.001 * feature.F9 + ...
        0.5 * feature.F10;
end

The feature set.

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.

  1. F1Mean levelmean(x)1
  2. F2Variancevar(x)2
  3. F3Total rise timeΣ tᵣ1
  4. F4Total response amplitudeΣ A0.5
  5. F5Response area, triangularΣ ½·A·tᵣ1
  6. F6Largest responsemax A2
  7. F7Rise time of the largest responsetᵣ at max A1
  8. F8Response countn5
  9. F9RMS level√mean(x²)0.001
  10. F10Mobility-style frequency(1/2π)·√(Σ Δx² / Σ x²)0.5

Index = F1 + 2·F2 + F3 + ½·F4 + F5 + 2·F6 + F7 + 5·F8 + 0.001·F9 + ½·F10

The entry point.

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.

Show main.m
main.mRawGitHub
% 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);
end

function printConditionSummary(result)
    fprintf('%s Features:\n', result.name);
    disp(result.features);
    fprintf('%s Fear Index: %.4f\n\n', result.name, result.fearIndex);
end

function 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});
        end
    end

    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');
    end
end

function 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;
end

function 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;
        end
    end

    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.

Repository