MATLAB Interface Wrapper

33 views
Skip to first unread message

Eric

unread,
Mar 31, 2014, 7:23:49 PM3/31/14
to nipy...@googlegroups.com
Hi All,

I had to wrap a MATLAB function/script for the first time today and grab the MATLAB command line output.  It was a bit painful based onm the two MATLAB wrapper examples on the Nipype site.  Hopefully this post will help someone else do the same in the future.

The below MATLAB function wrapper for Nipype ("read_string_from_mat.m") demonstrates a light wrapper for a function that reads an input MAT file and prints the string it finds based on a threshold value to the MATLAB command line.  Nipype then grabs up that MATLAB command line output and returns it as a string to "out_value".

Feel free to email me with questions or feedback.  Chris, Satra, if you guys like this perhaps it could be added to the MATLAB Wrapper documentation you already have?

--------------------------------------------------------
### read_string_from_mat.m wrapper for string output ###
class read_string_from_matInputSpec(MatlabInputSpec):
    script = traits.String(mandatory=False)
    in_file = traits.File(mandatory=True, exists=True, desc="MAT file to read.")
    threshold = traits.Float(mandatory=True, desc="look up threshold in results.")

class read_string_from_matOutputSpec(MatlabInputSpec):
    out_value = traits.String(desc='Output format string')

class read_string_from_mat(MatlabCommand):
    input_spec = read_string_from_matInputSpec
    output_spec = read_string_from_matOutputSpec
    
    def _my_script(self):
        arg_dict = dict(
            in_file = self.inputs.in_file,
            threshold = self.inputs.threshold
            )
        ### HARDCODED WARNING: addpath ###
        matlab_function = string.Template(
            """addpath('/path/to/matlab_scripts') ; out_value = read_string('$in_file', $threshold) ; disp(out_value) ; exit;"""
            ).substitute(arg_dict)
        return matlab_function
    
    def _run_interface(self, runtime):
        results = MatlabCommand(script=self._my_script(), mfile=True).run()
        return results.runtime
    
    def aggregate_outputs(self, runtime=None, needed_outputs=None):
        outputs = self._outputs()
        outputs.out_value = str(runtime.stdout.split('\n')[-2])
        return outputs
--------------------------------------------------------

Thanks,
~Eric
Reply all
Reply to author
Forward
0 new messages