Fwd: Re: [Eeglablist] importing from brain vision analyzer

Joseph Brooks jlbrooks at socrates.berkeley.edu
Thu Jan 6 19:21:44 PST 2005


>
>Brian,
>
>You can use the attached macro to export data from Analyzer to a .mat file.
>
>Joe
>
>At 02:05 PM 1/6/2005, you wrote:
>>I'm trying to import data using the Import Data-> From Brain Vis. Anal. 
>>MatLab file, but I cannot find any documentation on how to export from 
>>Brain Vision to a matlab file.  Could anyone direct me to a source or 
>>fill me in on brain vision's export to .MAT file feature?
>>
>>thanks,
>>Brian
>>
>>_______________________________________________
>>eeglablist mailing list eeglablist at sccn.ucsd.edu
>>http://sccn.ucsd.edu/mailman/listinfo/eeglablist
>>Eeglablist page: http://sccn.ucsd.edu/eeglab/eeglabmail.html
>>To unsubscribe, send an empty email to eeglablist-unsubscribe at sccn.ucsd.edu
-------------- next part --------------
' CreateMATFile - Create a Matlab5 compatible *.mat file from the current data set and markers.
' Author: Dr. Ingmar Gutberlet, (c) BlindSight Consulting, 2002 / Date of work start: 6.9.2002
' This macro includes adaptations of several routines from a macro named "Matlab" by Dr. Achim Hornecker.
' $Id: CreateMATFile.vabs,v 1.6 2002-09-07 20:53:35+01 gutberle Exp gutberle $
'---------------------------------------------------------------------------------------------------------
' SYNOPSIS: This macro automatically creates a Matlab5 compatible MAT file from the data of the
' currently active history node. -  The name of the file is built from the currently active history
' files's name and the currently active history nodes' name. The location for the MAT file is determined
' from the user constant "MatFileDir", which, if empty, defaults to the current export files folder.
' Please note that any spaces found in the file name are substituted by underscore characters "_".
'
' EEGDATA:  The way data is exported depends on the type of data present and on the status of the user 
'           variable "MatFileSegmented". If "MatFileSegmented" ist set to "True" and the dataset is found
'           to be segmented, all channel data is written to the MAT file as segmented data in a two
'           dimensional array CH(SegmentCount,SegmentDataPoints). For nonsegmented datasets, channel data
'           is written in form of a one-dimensional data vector.
'           Note: Even for segmented data, "MatFileSegmented" can be set to "False" in order to have data
'           written as a one-dimensional vector. Please note though, that there will be discontinuities
'           at the segment borders and that the time vector "t" (see below" will not reflect the times
'           within each segment, but the overall position of each datapoint. This is NOT the TIME of the
'           datapoints recording, but only a millisecond based index to the data vector.
'           Complex data is exported as complex data to Matlab and can be manipulated with the complex
'           algebra operations built into Matlab.
' MARKERS:  If data is written in nonsegmented fashion, markers are written in form of a one-dimensional
'           vector as well. Marker positions will be general pointers to the markers withing the dataset
'           in form of the data point count at the markers occurrence. If data is written in segmented
'           fashion, Markers will be written as a two-dimensional array MK(SegmentCount,SegmentMarkers).
'           If segmented markers are used, marker positions will be adjusted to pointers of the respective
'           marker's occurrence within the segment (not the dataset).
' TIMEAXIS: The time axis is always written as a one-dimensional vector of millisecond values, or in the
'           case of frequency values, as Hertz values. If EEGData is written in nonsegmented fashion, the
'           time or frequency axis is incremented for the entire length of the dataset. Please note that
'           this would produce wrong frequency values if the dataset was in fact segmented, but is to be
'           written in nonsegmented fashion. In these cases, where the user needs segmented data to be
'           written as nonsegmented vector data, the user must assure correct time/frequency information
'           to be used him/herself.
'           For time data, the x-Axis is named "t", for frequency data the vector is named f. The user
'           can use these vectors for correct plotting of data, for example 'plot(t, Fp1)' in matlab).
' CHANNELS: Here, channels means the polar channel positions. These data are written as structured arrays
'           with the polar coordinates RADIUS, THETA and PHI as well as the channels true name in form of
'           a structured array. Positions are written as a one-dimensional vector Channels(ChannelCount).
' 
' Additionally, the macro exports the following variables with general parameters of the dataset:
'
' ChannelCount : Number of channels in dataset.
' SegmentCount : Number of segments in dataset.
' MarkerCount  : Number of markers in dataset.
' SampleRate   : Sample rate of current dataset.
'
' Use matlab command 'whos' for a list of exported data.
'
' The user can use a small number of constants at the head of the macro code to modify the macro's
' operation of the macro. These constants, their meanings and default valuesare:
'
' Const MatFileDirectory = ""			' Directory for MAT files. Defaults to ExportFileFolder.
' Const MatFileSegmented = True			' Write data and markers into two dimensional arrays?
' Const MatlabWaitStart = 1				' Time to wait for Matlab to inititalize in seconds. 
'
' A new history node is created in order to make this macro available for calling from history templates.
' The new history normally has the name CreateMATFile. However, if a node or nodes by this name already
' exist(s), the node name is incremented starting with an index of 2, thus replicating Analyzer behavior.
'
' CONTACT: For any suggestions, questions or bug reports, please contact support at brainproducts.com
'----------------------------------------------------------------------------------------------------------
Const MatFileDirectory = "C:"				' Directory for MAT files. Defaults to ExportFileFolder.
Const MatFileSegmented = True			' Write data and markers into two dimensional arrays?
Const MatlabWaitStart = 1				' Time to wait for Matlab to inititalize in seconds.
'----------------------------------------------------------------------------------------------------------
Option Explicit

Const VersionID = "$Revision: 1.6 $"	' Macro revision, automatically updated by RCS repository.
Const ProgramID = "CreateMATFile"		' Name of the macro. Used for alerts and message boxes.

' Matlab variables...
Dim Matlab As Object					' Matlab object variable for OLE communication.
Dim MatlabCommand As String				' Matlab command string for markers, coordinates, commands.
Dim MatFilePath As String				' Path variable for newly created *.MAT files.
Dim MatFileNamePath As String			' File and path of newly created *.MAT file.
Dim MReal() As Double					' Complex data real part.
Dim MImag() As Double					' Complex data imaginary part.
Dim bComplex As Boolean					' Flag indicating if data is complex.
Dim bFreq As Boolean					' Flag indicating if data is frequency data.
' Dataset variables...
Dim ds As Dataset						' Dataset object. Points to ActiveNode
Dim mk As Marker						' Marker object for writing markers to Matlab.
Dim ch As Channel						' Channel object for writing channel positions to Matlab.
Dim pos As ChannelPosition				' Position object for writing channel positions to Matlab.
Dim nhn As New NewHistoryNode			' New history node object for dummy node creation.
Dim NewNodeName As String				' Name of history node to be created.
Dim DatasetLength As Long				' Length of current dataset as number of points.
Dim DatasetMaxLength As Long			' Length of longest segment with manually set segments.
Dim DataIsSegmented As Boolean			' Flag indicating whether data is properly segmented.
Dim SamplingInterval As Double			' Sample interval of current dataset.
Dim DataType As Long					' Current dataset's data type (time vs. frequency domain).
Dim DataPointNum As Long				' Currently processed data point.
Dim ChannelData() As Single				' Channel data array for copying data to Matlab.
Dim ChannelNum As Long					' Currently processed channel by number.
Dim ChannelCount As Long				' Total number of channels.
Dim ChannelName As String				' Name of current channel as seen by Matlab.
Dim ChannelNames() As String			' Array with original channel names from current dataset.
Dim ChannelPrefix As String				' Channel name prefix for nonalphanumeric channel names.
Dim MarkerNum As Long					' Currently processed marker by number.
Dim MarkerCount As Long					' Total number of markers in dataset.
Dim SegmentNum As Long					' Currently processed segment by number.
Dim SegmentCount As Long				' Total number of segments in dataset.
Dim SegmentMarkerNum As Long			' Currently processed marker for segmented data.
Dim SegmentMarkerCount As Long			' Number of markers in a given segment.
Dim SegmentDatasetStart () As Long		' Starting points of dataset segments in data points.
Dim SegmentDatasetLength () As Long		' Length of dataset segments in data points.
' Helper variables for GUI elements...
Dim PercentArray (0) As String			' Dummy Array for progress display.
Dim ProgressPhase As Long				' Phase of copying data, marker, ...

Sub Main

	' Initialize global error handling...
	On Error GoTo CheckError

	' Initialize some needed general variables...
	InitVariables

	' Create a matlab object
	MsgBoxNonModal ProgramID & "...", "Please wait while Matlab is being started..."
	
	' Clear the Matlab workspace
	MatlabCommand = "clear;"
	Matlab.Execute(MatlabCommand)

	' Check, if the node name CompareNodes already exists and change name accordingly...
	NewNodeName =  ValidChildNodeName(ActiveNode,ProgramID)

	' And set up the new history node for creation...
	nhn.Create NewNodeName, ActiveNode, "", True

	' Read the current dataset's properties...
	ReadDatasetProperties

	' Set the file name and path for the MAT file...
	MatFilePath = Trim(MatFileDirectory)
	If (MatFilePath = "") Then MatFilePath = CurrentWorkspace.ExportFileFolder
	If (Right(MatFilePath,1) = "\") Then MatFilePath = Left(MatFilePath,Len(MatFilePath)-1)
	If (Dir$(MatFilePath & "\*.*") = "") Then Error 1002
	MatFileNamePath = LCase(MatFilePath & "\" & Replace(ActiveNode.HistoryFile.Name & "_" & ActiveNode.Name & ".mat",Chr(32),"_"))
	
	' ShowProgress dialog which calls the actual data processing routines
	ShowProgressDialog ProgramID & "...", "Copying data to Matlab:"
	
	' Write markers to matlab
	ShowProgressDialog ProgramID & "...", "Copying markers to Matlab:"
	
	' And append the axis matrix to the existing MAT file...
	MatlabCommand = "save '" & MatFileNamePath & "' Markers -APPEND;"
    Matlab.Execute(MatlabCommand)		
    
    ' Check if we have a MAT file, else exit with error...
    If (Dir$(MatFileNamePath) = "") Then Error 1001
	
	' Write x-axis to matlab
	AxisToMatlab
	
	' Write coordinates to matlab
	CoordinatesToMatlab

	' Write coordinates to matlab
	DatasetParamsToMatlab

	' Build the description string for the new history node...
	BuildParamString
	
	' Clear all dynamically created variables...
	ClearVariables
	
	' Finish creating the new history node...
	nhn.Finish
	
	' Globally used error checking routines...
	CheckError:
	Beep
	Dim nError As Long
	nError = Err.Number And &h7fff	' Extract pure error code...
	Select Case nError
	Case 1001   ' Writing the *.mat file failes...
		MsgBox "Writing the *.mat file failed. - Please check your dataset for errors... !", vbCritical, ProgramID
	Case 1002   ' The directory for the MAT files does not exist...
		MsgBox "The directory you specified for the MAT files does not exist !", vbCritical, ProgramID
	Case 1503   ' No dataset open and selected
		MsgBox "This macro requires an active history node for operation!", vbCritical, ProgramID
	Case 10095  ' Matlab could not be started.
		MsgBox "Matlab could not be started - Please make sure Matlab is installed on this computer !", vbCritical, ProgramID
	Case Else	' Unexpected or unknown error occurred...
		MsgBox "Error No. " & nError & ": "&Error(nError) & "  Please contact the support team.", vbCritical, ProgramID
	End Select
	
End Sub

' Definition of the dialog to be shown during the processing of data...
Public Sub ShowProgressDialog(RunTitle As String, RunMessage As String)
	Begin Dialog UserDialog 310,63,RunTitle,.ProgressDialog ' %GRID:10,7,1,1
		Text 30,14,170,14,RunMessage,.RundlgTxt
		ListBox 200,11,70,21,PercentArray(),.PercentOK
		CancelButton 120,35,80,21
	End Dialog
	Dim Rundlg As UserDialog
	PercentArray(0) = "     00.0%"
	If Dialog(Rundlg) = 0 Then Exit All
End Sub

' Dialog function servicing the processing of data...
Public Function ProgressDialog%(DlgItem$, Action%, SuppValue%)
	Dim PercentFinished As Double
    Select Case Action%
    Case 1 ' Dialog box initialization
    	ProgressPhase = ProgressPhase + 1
    	ChannelNum = 0
    	MarkerNum = 0
    	SegmentNum = 0
    	DlgFocus "Cancel"
    Case 2 ' Value changing or button pressed
    	If (DlgItem$ = "Cancel") Then
    		ProgressDialog% = False ' exit the dialog
        End If
    Case 4 ' Focus changed
    Case 5 ' Idle
    	Select Case ProgressPhase
    		Case 1    		
    			PercentFinished = DataToMatlab
    		Case 2
    			PercentFinished = MarkersToMatlab
    	End Select
    	If PercentFinished <= 100.0 Then
    		PercentArray(0) = Format$(PercentFinished/100,"     00.0%")
    		DlgListBoxArray "PercentOK", PercentArray()
        	ProgressDialog% = (PercentFinished < 100.0)
        	If (ProgressDialog% = False) Then
        		DlgEnd 1000
        	End If
        Else 
        	ProgressDialog% = False
        	DlgEnd 1000
        End If
        DlgFocus "Cancel"
    Case 6 ' Function key
    End Select
End Function

' Definition of the dialog to be shown during the processing of data...
Public Sub MsgBoxNonModal(RunTitle As String, RunMessage As String)
	Begin Dialog UserDialog 310,63,RunTitle,.MsgBoxNonModalDialog ' %GRID:10,7,1,1
		Text 30,14,250,14,RunMessage,.RundlgTxt
		CancelButton 120,35,80,21
	End Dialog
	Dim Rundlg As UserDialog
	If Dialog(Rundlg) = 0 Then Exit All
End Sub

' Dialog function servicing the processing of data...
Public Function MsgBoxNonModalDialog%(DlgItem$, Action%, SuppValue%)
    Select Case Action%
    Case 1 ' Dialog box initialization
    	DlgFocus "Cancel"
    Case 2 ' Value changing or button pressed
    	If (DlgItem$ = "Cancel") Then
    		MsgBoxNonModalDialog% = False ' exit the dialog
        End If
    Case 5 ' Idle
    	MsgBoxNonModalAction
        MsgBoxNonModalDialog% = False
        DlgEnd 1000
    End Select
End Function

' Execute a command while the message box remains on screen...
Sub MsgBoxNonModalAction
	Dim StartTime As Double
	Set Matlab = CreateObject("Matlab.Application")
	Wait MatlabWaitStart
End Sub

' Read the dataset properties, channel names and data type...
Sub ReadDatasetProperties
	Set ds = ActiveNode.Dataset
	DataType = ds.Type
	SamplingInterval = ds.SamplingInterval
	ChannelCount = ds.Channels.Count
	MarkerCount = ds.Markers.Count
	SegmentCount = ActiveNode.Segments.Count
	DatasetLength = ds.Length
	DataIsSegmented = ((ds.SegmentationType <> viStNotSegmented) And (ds.Averaged = False))
	If ((MatFileSegmented = True) And (DataIsSegmented = True)) Then DatasetLength = (DatasetLength/ActiveNode.Segments.Count)
	ReDim SegmentDatasetStart(SegmentCount)
	ReDim SegmentDatasetLength(SegmentCount)
	' Establish the maximum segment size and the segment start points...
	If (MatFileSegmented = True) Then
		If (ds.SegmentationType = viStManual) Then
			If (DataIsSegmented = True) Then
				DatasetMaxLength = 0
				For SegmentNum = 1 To SegmentCount
					If (ActiveNode.Segments(SegmentNum).Dataset.Length > DatasetMaxLength) Then
						DatasetMaxLength = ActiveNode.Segments(SegmentNum).Dataset.Length
					End If
				Next SegmentNum
			Else
				DatasetMaxLength = DatasetLength
			End If
			' Establish the segment start and time0 points...
			SegmentNum = 0
			For MarkerNum = 1 To MarkerCount
				Set mk = ds.Markers(MarkerNum)
				' Record the new segment position...
				If (mk.Type = "New Segment") Then
					SegmentNum = SegmentNum + 1
					SegmentDatasetStart(SegmentNum) = mk.Position
					SegmentDatasetLength(SegmentNum) = ActiveNode.Segments(SegmentNum).Dataset.Length
				End If
			Next MarkerNum
		Else
			' Dataset either is not segmented or segmented into equal sized segments...
			For SegmentNum = 1 To SegmentCount
				SegmentDatasetStart(SegmentNum) = (((SegmentNum-1)*DatasetLength)+1)
				SegmentDatasetLength(SegmentNum) = DatasetLength	
			Next SegmentNum
			' And finally, set the maximum dataset length to one segment's length...
			DatasetMaxLength = DatasetLength
		End If
	Else
		DatasetMaxLength = DatasetLength
	End If
	' Collect the channel names and make Matlab compatible...
	ReDim ChannelNames(1 To ChannelCount)
	For ChannelNum = 1 To ChannelCount
		ChannelNames(ChannelNum) = ds.Channels(ChannelNum).Name
		Dim a As Integer
		a = Asc(Left(ChannelNames(ChannelNum), 1))
		If Not((Asc("a") <= a And a <= Asc("z")) Or (Asc("A") <= a And a <= Asc("Z"))) Then ChannelPrefix = "C"
	Next ChannelNum
	If DataType = viDtTimeDomainComplex Or DataType = viDtFrequencyDomainComplex Then
		bComplex = True
	Else
		bComplex = False
	End If
	If DataType = viDtFrequencyDomain Or DataType = viDtFrequencyDomainComplex Then
		bFreq = True
	Else
		bFreq = False
	End If
End Sub

' Write current history node's data to Matlab...
Function DataToMatlab
	' Increment the channel number with each call of the function...
	ChannelNum = ChannelNum + 1
	' Clear the Matlab workspace for the new channel data...
	MatlabCommand = "clear;"
    Matlab.Execute(MatlabCommand)	
	' If this is the first channel, then redim the arrays...
	If ChannelNum = 1 Then
		If ((MatFileSegmented = True) And (DataIsSegmented = True)) Then
			ReDim MReal(SegmentCount-1,DatasetMaxLength-1)
    		If bComplex Then ReDim MImag(SegmentCount-1,DatasetMaxLength-1)
    	Else
    		ReDim MReal(DatasetLength-1)
    		If bComplex Then ReDim MImag(DatasetMaxLength-1)
    	End If
	End If
	' Get the channel data, and fill the Matlab matrix...
    If ((MatFileSegmented = True) And (DataIsSegmented = True)) Then
	    For SegmentNum = 1 To SegmentCount
		    ActiveNode.Dataset.Channels(ChannelNum).GetData SegmentDatasetStart(SegmentNum), SegmentDatasetLength(SegmentNum), ChannelData
		    If (DatasetMaxLength > SegmentDatasetLength(SegmentNum)) Then ReDim Preserve ChannelData(DatasetMaxLength)
		    For DataPointNum = 1 To DatasetMaxLength
		    	If bComplex Then
		        	MReal(SegmentNum-1,DataPointNum-1) = ChannelData(2*DataPointNum-1)
		        	MImag(SegmentNum-1,DataPointNum-1) = ChannelData(2*DataPointNum)
		    	Else
		        	MReal(SegmentNum-1,DataPointNum-1) = ChannelData(DataPointNum)
		        End If
		    Next DataPointNum
		Next SegmentNum
	Else
		ActiveNode.Dataset.Channels(ChannelNum).GetData 1, DatasetLength, ChannelData
	    For DataPointNum = 1 To DatasetLength
	    	If bComplex Then
	        	MReal(DataPointNum-1) = ChannelData(2*DataPointNum-1)
	        	MImag(DataPointNum-1) = ChannelData(2*DataPointNum)
	    	Else
	        	MReal(DataPointNum-1) = ChannelData(DataPointNum)
	        End If
	    Next DataPointNum
	End If
    ChannelName = ChannelPrefix + ChannelNames(ChannelNum)
    Matlab.PutFullMatrix ChannelName, "base", MReal, MImag
    ' And append or write the new variable to the MAT file...
    If ChannelNum = 1 Then
    	MatlabCommand = "save '" & MatFileNamePath & "' " & ChannelName & ";"
	Else
		MatlabCommand = "save '" & MatFileNamePath & "' " & ChannelName & " -APPEND;"
	End If
    Matlab.Execute(MatlabCommand)	
    ' Check if we have a MAT file, else exit with error...
    If (Dir$(MatFileNamePath) = "") Then Error 1001
    ' Establish the percentage of channels finished...
    DataToMatlab = ((ChannelNum/ChannelCount)*100)
End Function

' Write current history node's markers to Matlab...
Function MarkersToMatlab	
	If ((MatFileSegmented = True) And (DataIsSegmented = True)) Then
		SegmentNum = SegmentNum + 1
		SegmentMarkerCount = ActiveNode.Segments(SegmentNum).Dataset.Markers.Count
		For SegmentMarkerNum = 1 To SegmentMarkerCount
			MarkerNum = MarkerNum + 1
			Set mk = ActiveNode.Segments(SegmentNum).Dataset.Markers(SegmentMarkerNum)
			' Write channel number
			MatlabCommand = "Markers(" + Trim(Str(SegmentNum)) & "," & Trim(Str(SegmentMarkerNum)) + ").Chan = " + Trim(Str(mk.ChannelNumber)) + ";"
			Matlab.Execute(MatlabCommand)
			' Write Description
			MatlabCommand = "Markers(" + Trim(Str(SegmentNum)) & "," & Trim(Str(SegmentMarkerNum)) + ").Description = '" + Trim(mk.Description) + "';"
			Matlab.Execute(MatlabCommand)
			' Write Points
			MatlabCommand = "Markers(" + Trim(Str(SegmentNum)) & "," & Trim(Str(SegmentMarkerNum)) + ").Points = " + Trim(Str(mk.Points)) + ";"
			Matlab.Execute(MatlabCommand)
			' Write Position
			MatlabCommand = "Markers(" + Trim(Str(SegmentNum)) & "," & Trim(Str(SegmentMarkerNum)) + ").Position = " + Trim(Str(mk.Position-SegmentDatasetStart(SegmentNum)+1)) + ";"
			Matlab.Execute(MatlabCommand)
			' Write Type
			MatlabCommand = "Markers(" + Trim(Str(SegmentNum)) & "," & Trim(Str(SegmentMarkerNum)) + ").Type = '" + Trim(mk.Type) + "';"
			Matlab.Execute(MatlabCommand)	
		Next SegmentMarkerNum
	Else	
		MarkerNum = MarkerNum + 1
		Set mk = ActiveNode.Dataset.Markers(MarkerNum)
		' Write channel number
		MatlabCommand = "Markers(" + Str(MarkerNum) + ").Chan = " + Trim(Str(mk.ChannelNumber)) + ";"
		Matlab.Execute(MatlabCommand)
		' Write Description
		MatlabCommand = "Markers(" + Str(MarkerNum) + ").Description = '" + Trim(mk.Description) + "';"
		Matlab.Execute(MatlabCommand)
		' Write Points
		MatlabCommand = "Markers(" + Str(MarkerNum) + ").Points = " + Trim(Str(mk.Points)) + ";"
		Matlab.Execute(MatlabCommand)
		' Write Position
		MatlabCommand = "Markers(" + Str(MarkerNum) + ").Position = " + Trim(Str(mk.Position)) + ";"
		Matlab.Execute(MatlabCommand)
		' Write Type
		MatlabCommand = "Markers(" + Str(MarkerNum) + ").Type = '" + Trim(mk.Type) + "';"
		Matlab.Execute(MatlabCommand)	
	End If
    ' Establish the percentage of markers finished...	
	If ((MatFileSegmented = True) And (DataIsSegmented = True)) Then
		MarkersToMatlab = ((SegmentNum/SegmentCount)*100)
	Else
		MarkersToMatlab = ((MarkerNum/MarkerCount)*100)
	End If
End Function

' Write current history node's time or frequency axis to Matlab...
Sub AxisToMatlab
	Dim AxisMatrixName As String
	Dim Time0Pos As Long
	Dim AxisStartTime As String
	Dim AxisStopTime As String
	Dim AxisIncrement As String
	' Clear the Matlab workspace for the axis matrix data...
	MatlabCommand = "clear;"
    Matlab.Execute(MatlabCommand)	
	' Find the time 0 time point...
	Time0Pos = FindTime0 - 1	
	' Set the start and stop times
	If bFreq Then
		AxisMatrixName = "f"
       	AxisStartTime = Trim(Str(-(Time0Pos) * SamplingInterval))
       	AxisStopTime = Trim(Str(((DatasetLength-1) - Time0Pos) *  SamplingInterval))
       	AxisIncrement = Trim(Str(SamplingInterval))
    Else
    	AxisMatrixName = "t"
       	AxisStartTime = Trim(Str(-(Time0Pos) * SamplingInterval * 1e-3))
       	AxisStopTime = Trim(Str(((DatasetLength-1) - Time0Pos) * SamplingInterval * 1e-3))
       	AxisIncrement = Trim(Str((SamplingInterval * 1e-3)))
    End If
	' Write the axis time or frequency matrix and transpose it...
	MatlabCommand = AxisMatrixName & "=" & AxisStartTime & ":" & AxisIncrement & ":" & AxisStopTime & ";"
	Matlab.Execute(MatlabCommand)
	MatlabCommand = AxisMatrixName & "=" & AxisMatrixName & "';"
	Matlab.Execute(MatlabCommand)
	' And append the axis matrix to the existing MAT file...
	MatlabCommand = "save '" & MatFileNamePath & "' " & AxisMatrixName & " -APPEND;"
    Matlab.Execute(MatlabCommand)		
    ' Check if we have a MAT file, else exit with error...
    If (Dir$(MatFileNamePath) = "") Then Error 1001
End Sub

' Write current history nodes' coordinates to Matlab...
Sub CoordinatesToMatlab
	' Clear the Matlab workspace for the axis matrix data...
	MatlabCommand = "clear;"
    Matlab.Execute(MatlabCommand)	
    ' And run through all channels, collecting the coordinates into the Matlab matrix...
	For ChannelNum = 1 To ChannelCount
		Set Pos = ds.Channels(ChannelNum).Position
		MatlabCommand = "Channels(" + Str(ChannelNum) + ").Phi = " + Str(Pos.Phi) + ";"
		Matlab.Execute(MatlabCommand)
		MatlabCommand = "Channels(" + Str(ChannelNum) + ").Theta = " + Str(Pos.Theta) + ";"
		Matlab.Execute(MatlabCommand)
		MatlabCommand = "Channels(" + Str(ChannelNum) + ").Radius = " + Str(Pos.Radius) + ";"
		Matlab.Execute(MatlabCommand)
		MatlabCommand = "Channels(" + Str(ChannelNum) + ").Name = '" + ds.Channels(ChannelNum).Name + "';"
		Matlab.Execute(MatlabCommand)
	Next
	' And append the axis matrix to the existing MAT file...
	MatlabCommand = "save '" & MatFileNamePath & "' Channels -APPEND;"
    Matlab.Execute(MatlabCommand)
	' Check if we have a MAT file, else exit with error...
    If (Dir$(MatFileNamePath) = "") Then Error 1001
End Sub

' Write current history nodes' coordinates to Matlab...
Sub DatasetParamsToMatlab
	' Clear the Matlab workspace for the axis matrix data...
	MatlabCommand = "clear;"
    Matlab.Execute(MatlabCommand)	
    ' Set and save some general variables to the MAT file...
	MatlabCommand = "ChannelCount = " + Trim(Str(ChannelCount)) + ";"
	Matlab.Execute(MatlabCommand)
	MatlabCommand = "SegmentCount = " + Trim(Str(SegmentCount)) + ";"
	Matlab.Execute(MatlabCommand)
	MatlabCommand = "MarkerCount = " + Trim(Str(MarkerCount)) + ";"
	Matlab.Execute(MatlabCommand)	
	MatlabCommand = "SampleRate = " + Trim(Str(1000000/SamplingInterval)) + ";"
	Matlab.Execute(MatlabCommand)	
	' And append the axis matrix to the existing MAT file...
	MatlabCommand = "save '" & MatFileNamePath & "' ChannelCount SegmentCount MarkerCount SampleRate -APPEND;"
    Matlab.Execute(MatlabCommand)
	' Check if we have a MAT file, else exit with error...
    If (Dir$(MatFileNamePath) = "") Then Error 1001
End Sub

' Find the first Time0 marker in this dataset...
Function FindTime0() As Long
	Dim Pos As Long
	Pos = 1
	For MarkerNum = 1 To MarkerCount
		Set mk = ds.Markers(MarkerNum)
		If mk.Type = "Time 0" Then
			Pos = mk.Position
			Exit For
		End If
	Next
	FindTime0 = Pos
End Function

' Build the NewHistoryNode description string...
Function BuildParamString As String
	Dim nhnString As String
	nhnString = "*** " & ProgramID & " - Version " & Mid$(VersionID,12,InStr(12,VersionID," ")-12) & " / Dr. Ingmar Gutberlet, (c) BlindSight Consulting, 2002 ***" & vbCrLf
	nhnString = nhnString & "-------------------------------------------------------------------------------------------" & vbCrLf
	nhnString = nhnString & vbCrLf
	nhnString = nhnString & "MAT file was written to: " & MatFileNamePath & vbCrLf & vbCrLf
	nhn.Description = nhnString
End Function

' Takes a history node name and searches the child node names for the next valid node name...
Function ValidChildNodeName (SearchNode As HistoryNode, SearchName As String) As String
	Dim hnChild As HistoryNode
	Dim hnChildNum As Long
	Dim SearchNameExt As String
	Dim FileCount As Long
	FileCount = 1
	SearchNameExt = ""
	Do 
		For hnChildNum = 1 To SearchNode.HistoryNodes.Count
			If (SearchNode.HistoryNodes(hnChildNum).Name = SearchName & SearchNameExt) Then
				FileCount = FileCount + 1
				SearchNameExt = " " & FileCount
				Exit For
			End If
		Next hnChildNum
	Loop Until (hnChildNum > SearchNode.HistoryNodes.Count)
	 ValidChildNodeName = SearchName & SearchNameExt
End Function

' Initialize some needed general variables...
Sub InitVariables
	ChannelPrefix = ""
	ProgressPhase = 0
End Sub

' Clear all dynamically allocated variables and objects...
Sub ClearVariables
	Set Matlab = Nothing
	Set ds = Nothing
	Set mk = Nothing
	Set ch = Nothing
	Set pos = Nothing
	Erase ChannelData
	Erase MReal
	Erase MImag
	Erase ChannelNames
	Erase SegmentDatasetStart
	Erase SegmentDatasetLength
End Sub


More information about the eeglablist mailing list