ERP Peak Detective: Introduction to Event-Related Potential Analysis with MATLAB
Summary
This scaffolded laboratory activity introduces students with minimal programming experience to Event-Related Potential (ERP) analysis using MATLAB. Students progress from interactive visual exploration of neural data to writing their first complete analysis script. Using a fill-in-the-blank template, students learn to load ERP data, create publication-quality plots, automatically detect the P300 component (a key neural response), and measure peak amplitude and latency. The activity emphasizes the transition from manual to automated analysis while building fundamental MATLAB skills including data visualization, function usage, array indexing, and script development. Students validate their automated measurements against visual inspection, learning both technical coding skills and scientific practices. The activity includes synthetic but realistic P300 data, complete teaching materials, and assessment tools.
Keywords: event-related potentials, ERP, neuroscience, cognitive psychology, data analysis, peak detection, automated measurement, data visualization, electroencephalography, EEG, P300, scaffolded learning, beginner programming
Learning Goals
CONTENT LEARNING GOALS:
Neuroscience Concepts:
- Understand Event-Related Potentials as time-locked neural responses
- Recognize the P300 component and its characteristics (timing, amplitude, functional significance)
- Learn to measure ERP features: amplitude (magnitude of response) and latency (timing of response)
- Understand why both measures are scientifically important
- Appreciate the value of automated vs. manual measurement approaches
MATLAB SKILLS:
Fundamental Programming:
- Load data from .mat files using the load() command
- Create scientific visualizations with proper labels, titles, and units
- Use functions with multiple output arguments (e.g., max())
- Work with array indexing to access specific data points
- Add visual elements to plots (markers, reference lines)
- Structure and organize code with comments and sections
- Run complete scripts from start to finish
How MATLAB Improves Learning:
MATLAB is particularly well-suited for this activity because:
1. It handles matrix operations naturally (ERP data is inherently multi-dimensional)
2. Built-in visualization tools create publication-quality figures easily
3. The .mat file format is standard in neuroscience research
4. MATLAB is widely used in neuroscience labs, making these skills directly transferable
5. Interactive features (Data Cursor tool) allow visual exploration before coding
6. While other tools (Python, R) could accomplish similar goals, MATLAB's integrated environment and neuroscience toolboxes (EEGLAB, FieldTrip) make it the standard for ERP analysis
HIGHER-ORDER THINKING SKILLS:
Critical Thinking:
- Validate automated results against manual observations
- Evaluate whether peak measurements are physiologically plausible
- Identify limitations of automated peak detection
- Consider situations where automated methods might fail
Data Analysis:
- Progress from visual pattern recognition to quantitative measurement
- Interpret numerical results in scientific context
- Understand trade-offs between manual and automated approaches
Scientific Practice:
- Implement reproducible analysis workflows
- Document analysis steps through code comments
- Create figures suitable for scientific communication
- Develop systematic approaches to data exploration
Problem-Solving:
- Debug code errors using error messages
- Break complex problems into smaller steps
- Use documentation to learn new functions
- Adapt provided code for new purposes
OTHER SKILLS DEVELOPED:
- Scientific visualization: Creating clear, informative plots with appropriate labels and units
- Technical communication: Interpreting code, reading error messages, writing code comments
- Computational thinking: Understanding algorithm logic (how max() finds peaks)
- Self-efficacy: Building confidence through successful completion of first script
- Collaboration: Optional pair programming reinforces teamwork
Context for Use
This activity is designed for undergraduate students in introductory cognitive neuroscience, psychology, or neuroscience courses at the lower or upper division level. It works well in laboratory sections of 10-30 students and can be completed in a single 50-70 minute lab session. The activity is specifically designed for students with minimal or no prior programming experience.
MATLAB Technical Skills Required:
- Ability to open and run M-files (basic MATLAB navigation)
- Familiarity with the MATLAB interface (optional but helpful)
- NO prior programming experience required
The activity uses extensive scaffolding through:
1. Pre-written code that students run to explore data interactively
2. A fill-in-the-blank template with detailed hints and comments
3. Built-in validation checks that help students verify their work
4. Progressive difficulty from simple (labels) to moderate (function usage) challenges
Disciplinary Prerequisites:
- Basic understanding of what Event-Related Potentials represent (can be taught in pre-lab)
- Familiarity with the concept of neural responses to stimuli
- Understanding of time-locked brain activity (brief introduction sufficient)
Course Context:
This activity is ideal as:
- An introduction to quantitative methods in cognitive neuroscience courses
- A first computational laboratory in psychology research methods courses
- An early activity in a computational neuroscience sequence
- A standalone introduction to MATLAB in neuroscience contexts
The activity is positioned early in a course, typically after students have learned about ERPs conceptually but before they conduct their own ERP experiments. It serves as a bridge between theoretical knowledge and practical data analysis skills.
Adaptability:
The activity is highly adaptable:
- Can be modified for other ERP components (N170, N400, MMN)
- Template structure can be applied to any time-series peak detection
- Easily extended with follow-up activities (comparing conditions, multiple subjects)
- Can use real data if available with appropriate IRB approval
- Difficulty can be adjusted by providing more or less complete code
Description and Teaching Materials
ACTIVITY OVERVIEW:
This two-part laboratory activity guides students from interactive data exploration to writing their first MATLAB analysis script. Students work with synthetic Event-Related Potential data from a classic "oddball" paradigm and learn to automatically detect and measure the P300 component.
PART A: VISUAL EXPLORATION (15 minutes)
Students begin by loading pre-processed ERP data and creating basic plots using simple MATLAB commands provided by the instructor. They use MATLAB's interactive Data Cursor tool to manually identify the P300 peak and record its amplitude and latency on a worksheet. This phase builds intuition about the data structure and establishes expected results before programming.
PART B: SCRIPTED ANALYSIS (35-45 minutes)
Students receive a fill-in-the-blank template script (ERP_analysis_template.m) with approximately 80% of the code already written. They complete specific sections marked with "STUDENT:" comments, progressing through:
1. Plot formatting (adding labels, titles with units) - Easy
2. Peak detection using max() function - Medium difficulty
3. Adding visual markers to highlight the detected peak - Medium difficulty
4. Adding reference lines (baseline, stimulus onset) - Easy
The template includes:
- Extensive comments explaining each section's purpose
- Specific hints for each blank (e.g., "Hint: Use the max() function")
- Built-in validation checks that confirm results are physiologically reasonable
- References to MATLAB documentation for key functions
HOW MATLAB IS USED:
Data Management:
- load() function imports pre-processed ERP data from .mat file
- Variables include time vector (ms), voltage vector (μV), and metadata
Visualization:
- plot() creates line graphs of voltage over time
- Interactive Data Cursor tool enables manual peak identification
- xline() and yline() add reference markers
- Figure annotation with xlabel(), ylabel(), title(), legend()
Analysis:
- max() function automatically finds peak amplitude and its temporal position
- Array indexing converts position to actual time value
- fprintf() displays results in Command Window
Validation:
- Conditional logic checks if peak timing is physiologically plausible (250-600 ms for P300)
- Confirms amplitude polarity (positive for P300 component)
WHY MATLAB VS. OTHER SOFTWARE:
While similar activities could be implemented in Python or R, MATLAB offers distinct advantages:
1. Industry standard in neuroscience research (EEGLAB, FieldTrip toolboxes)
2. Integrated environment reduces cognitive load for beginners
3. Excellent visualization capabilities with minimal code
4. Matrix operations are intuitive (ERP data is naturally matrix-structured)
5. Wide institutional adoption means better student access
6. Interactive tools (Data Cursor, plot editor) support exploration-to-coding workflow
MATERIALS PROVIDED:
All materials are included and ready to use:
1. generate_P300_data.m - MATLAB script instructors run to create realistic synthetic ERP data. Generates P300_data.mat with time, voltage, and metadata. Commented code shows how synthetic ERPs are created from Gaussian components plus noise.
2. P300_data.mat - Sample dataset containing:
- time: 250 samples from -200 to 800 ms
- voltage: ERP amplitude in microvolts with realistic P300 (~350 ms, ~8 μV)
- electrode_name: 'Pz' (standard P300 recording site)
- condition: 'Target' (oddball paradigm)
3. ERP_analysis_template.m - Student fill-in-the-blank script with:
- Complete structure from data loading to validation
- ~20% blanks strategically placed at key learning points
- Detailed comments and hints for each section
- Seven progressive sections with increasing complexity
- Built-in validation checks
4. ERP_analysis_SOLUTION.m - Instructor reference showing completed code with:
- All blanks filled correctly
- Additional alternative approaches in bonus section
- Comments explaining pedagogical choices
5. Student Handout (PDF) - Complete activity instructions including:
- Learning objectives and background on P300
- Step-by-step instructions for both parts
- Fill-in-the-blank hints and common error solutions
- Grading rubric and deliverables checklist
- Optional challenge problems for advanced students
6. Student Worksheet - Assessment tool with:
- Questions for Part A visual exploration
- Spaces to record automated measurements
- Conceptual questions about ERP analysis
- MATLAB skills self-assessment
- Reflection prompts
7. Instructor Teaching Guide - Comprehensive documentation including:
- Minute-by-minute timeline with suggested dialogue
- Common student errors and troubleshooting solutions
- Detailed grading rubric
- Extension activities for fast finishers
- Adaptations for online delivery
- Assessment data tracking recommendations
8. MATLAB Quick Reference - Student cheat sheet covering:
- Essential commands for this activity
- Array indexing examples
- Common error messages and fixes
- Color/marker codes for plotting
FILE FORMATS:
- MATLAB scripts provided as .m files (editable)
- Student handout as markdown (easily converted to PDF/Word)
- Data as .mat (standard MATLAB format)
- Documentation as markdown for easy modification
All materials are designed for free redistribution under Creative Commons licensing.
ERP Peak Detective - Instructor Teaching Guide (Acrobat (PDF) 76kB Oct7 25)
Data Generation Script (Matlab File 5kB Oct7 25)
ERP Script (Matlab File 5kB Oct7 25)
Teaching Notes and Tips
IMPLEMENTATION TIPS:
Pre-Class Setup (30 minutes):
1. Run generate_P300_data.m to create sample data
2. Test solution script to verify all outputs
3. Upload P300_data.mat and ERP_analysis_template.m to course system
4. Print or distribute student handout and worksheet
5. Verify MATLAB installation on lab computers
During Class - Key Moments:
Introduction (5 min):
- Show example ERP plot to build interest
- Emphasize this is their first complete script
- Set expectation: "You'll be surprised how much you can do!"
Part A Monitoring:
- Circulate to ensure everyone can load data successfully
- Common issue: Students in wrong folder - teach Current Folder navigation
- Use Data Cursor tool demo if students struggle
- Expected measurements: ~350 ms, ~8 μV (accept ±10% range)
Part B Critical Points:
Section 1 (Labels): Quick win for confidence
- Most students complete easily
- Emphasize including units in labels
Section 2 (max function): Primary learning moment
- EXPECT confusion about multiple outputs - this is normal
- Draw on board: [value, position] = max(array)
- Key insight: "max() tells you the value AND where it is"
- Common error: Students write max(time) instead of max(voltage)
- Walk through: "We want the MAX voltage, then look up its TIME"
Section 3 (Marker): Second major challenge
- Students often forget hold on
- Common error: plot(peak_amplitude, peak_time) - backwards!
- Visual debugging: "If you don't see the marker, check colors"
- Try larger marker size if visibility is an issue
Section 4 (Reference lines): Usually straightforward
- Quick completion; use for catching up if behind
COMMON AREAS OF CONFUSION:
1. Multiple Output Arguments:
Why it's confusing: Students expect one answer from a function
How to help: Physical analogy - "I ask 'What's the tallest building?' You tell me both the height AND which building"
Reinforcement: Show help max to see documentation
2. Array Indexing:
Why it's confusing: Indirect lookup (use position to find time)
How to help: Simple example on board with numbered list
Analogy: "If I tell you the winner is in position 5, you look up who's in position 5"
3. Hold On/Off:
Why it's confusing: Unclear why it's needed
How to help: "MATLAB erases the plot each time unless you say 'hold on'"
Demonstration: Show what happens without it
4. Case Sensitivity:
Why it's confusing: Students may be used to case-insensitive languages
How to help: "Voltage and voltage are different to MATLAB"
SUGGESTIONS FOR HELPING STUDENTS USE MATLAB:
For Beginners:
- Emphasize reading error messages - they usually tell you what's wrong
- Teach "help function_name" early
- Encourage saving frequently
- Normalize errors: "Errors are how we learn, not failures"
Pacing Strategies:
- If class is moving fast: Introduce Challenge problems
- If class is slow: Work through Section 2 together as group
- Mixed speeds: Pair fast/slow students for peer teaching
Code Style Reinforcement:
- Praise good comments when you see them
- Model reading code out loud: "This line loads the data..."
- Emphasize that clear code is professional code
SAFETY/LOGISTICS:
- No safety concerns for this activity
- Ensure adequate computer access (1-2 students per computer works)
- Have backup data files on USB in case of network issues
- Keep solution script open on instructor computer for quick debugging
- Budget 5 extra minutes for technical difficulties
MAKING BEST USE OF THE ACTIVITY:
Progressive Skill Building:
- This activity introduces foundational skills used in all subsequent MATLAB work
- Explicitly connect to future activities: "Next time we'll compare TWO conditions using these same skills"
Metacognition:
- Ask students: "What strategy did you use when you got stuck?"
- Discuss: "How did you know your answer was right?"
- Emphasize learning process over perfect code
Common Pitfalls to Avoid:
- Don't skip Part A - visual exploration builds essential intuition
- Don't rush Section 2 - understanding max() is crucial
- Don't show solution too quickly - productive struggle is valuable
- Don't grade on speed - emphasize understanding over finishing
Extensions for Different Contexts:
- Neuroscience majors: Add more detail about P300 functional significance
- Psychology students: Connect to cognitive theories of attention/memory
- Computer science minors: Challenge them to optimize the code
- Pre-med students: Discuss clinical applications of ERPs
Online Adaptations:
- Synchronous: Use breakout rooms for Section B, share screens for help
- Asynchronous: Record Part A demonstration, provide extra video hints
- Both: Discussion forum for troubleshooting, virtual office hours during lab time
Assessment
Students are assessed on multiple dimensions using a 25-point rubric:
DELIVERABLES:
1. Completed MATLAB script (must run without errors)
2. Output figure saved as .png or .fig file
3. Completed worksheet with Part A observations and reflection
4. (Optional) Video screencast showing script execution
ASSESSMENT CRITERIA:
Technical Functionality (10 points):
- Script Execution (5 pts): Script runs completely without errors
- Correct Calculations (5 pts): Peak amplitude and latency within 10% of expected values (~350 ms, ~8 μV)
Instructor runs each student's script to verify functionality. Automated testing possible by checking if peak_amplitude and peak_time variables exist and are reasonable.
Scientific Visualization (10 points):
- Plot Formatting (5 pts): Proper axis labels with units, descriptive title, readable font size
- Peak Marker (3 pts): Red marker clearly visible at correct peak location
- Reference Lines (2 pts): Baseline (0 μV) and stimulus onset (0 ms) marked
Assessed visually from submitted figures. Students use File > Save As to export.
Code Quality (3 points):
- Clear comments explaining what each section does
- Readable code with appropriate spacing
- Logical organization following template structure
Assessed during script review. Emphasizes professional coding practices.
Conceptual Understanding (2 points):
- Worksheet questions answered thoughtfully
- Demonstrates understanding of ERP concepts and MATLAB functions
- Reflection shows metacognitive awareness
Assessed from worksheet responses. Key indicators: Can explain why automated detection is useful, identify potential limitations, articulate what they learned.
FORMATIVE ASSESSMENT DURING ACTIVITY:
Circulation Checks:
- Monitor Part A to ensure students can load data and create basic plots
- Check Section 2 completion to verify understanding of max() function
- Observe whether students are debugging independently or getting stuck
Validation Checks:
- Built-in script validation provides immediate feedback
- Students see if their peak is in expected range
- Encourages self-correction before submission
ASSESSMENT ALTERNATIVES:
For larger classes:
- Peer review of figures using checklist
- Automated testing of key variables
- Random sampling of scripts for detailed review
For skill-focused assessment:
- Take-home completion with higher expectations
- Add presentation requirement (show figure, explain approach)
- Portfolio inclusion for longitudinal skill tracking
SUCCESS INDICATORS:
- 90%+ of students complete working script
- Average peak measurements within 15% of expected values
- Students report increased confidence in MATLAB (self-assessment)
- Few requests to abandon MATLAB in future activities
References and Resources
SUPPORTING RESOURCES FOR FACULTY:
ERP Background and Methods:
- Luck, S. J. (2014). An Introduction to the Event-Related Potential Technique (2nd ed.). MIT Press.
Comprehensive textbook covering ERP methodology; Chapter 1 provides accessible introduction suitable for assigning as pre-reading.
- Kappenman, E. S., & Luck, S. J. (Eds.). (2011). The Oxford Handbook of Event-Related Potential Components. Oxford University Press.
Detailed reference on specific ERP components including P300; useful for instructor background.
Open ERP Datasets (for creating follow-up activities with real data):
- ERP CORE: https://erpinfo.org/erp-core
Free, well-documented ERP datasets from seven different paradigms including P300. Suitable for advanced versions of this activity using real data. Includes processing scripts and detailed documentation.
- OpenNeuro: https://openneuro.org
Repository of open neuroscience datasets including EEG/ERP studies. Requires more preprocessing but provides authentic research data. Search for "ERP" or "oddball" paradigms.
P300 Component Background:
- Polich, J. (2007). "Updating P300: An integrative theory of P3a and P3b." Clinical Neurophysiology, 118(10), 2128-2148.
Review article on P300 theory and applications; accessible to undergraduates. Useful for students wanting deeper understanding of the component they're measuring.
- Luck, S. J., & Kappenman, E. S. (2012). "ERP Components and Selective Attention." In The Oxford Handbook of Event-Related Potential Components.
Specifically addresses attention-related components including P300. Provides context for why amplitude and latency measurements are scientifically meaningful.
RELATED TEACHING ACTIVITIES:
While this activity is designed to be self-contained, it connects naturally to:
- Signal processing fundamentals (filtering, Fourier analysis)
- Statistical comparison of conditions (t-tests on ERP amplitudes)
- Batch processing and automation (analyzing multiple subjects)
- Advanced ERP analysis (time-frequency decomposition, topographic mapping)