Wednesday, March 24, 2010

[matlabjoystick] Use a Joystick in Matlab

Have you ever wanted to use a joystick in Matlab? Yeah, I didn't think so. But just in case you did I wrote a Mex file to interface with SDL's joystick subsystem. By the way, SDL is a great easy to use library, I recommend it.

I wrote this for the "remote control wheelchair" my lab is working on. At first I tried using keyboard control, but the binary nature of a keypress made it difficult to set a constant speed. I can't image many people using this, but it could be useful in some situations.

Basically a joystick object gets initialized, and sends back an array of doubles, one for each axis, hat, and button. Optionally a mask can be set to filter buttons. For example my joystick has 14 axes/buttons, but I only care about the first two axes and the trigger button.

The following Matlab session demonstrates the use of a joystick object.

>> j = Joystick(0)
j =
Joystick handle

Properties:
joystick_number: 0
state_mask: [1 1 1 1 1 1 1 1 1 1 1 1 1 1]
Methods, Events, Superclasses
>> j.state()
ans =
Columns 1 through 11
0 0 0 0 0 0 0 0 0 0 0
Columns 12 through 14
0 0 0
>> m = j.state_mask
m =
Columns 1 through 11
1 1 1 1 1 1 1 1 1 1 1
Columns 12 through 14
1 1 1
>> m(5:end) = zeros; m(3) = 0;
>> m
m =
Columns 1 through 11
1 1 0 1 0 0 0 0 0 0 0
Columns 12 through 14
0 0 0
>> j.mask(m)
>> j.state()
ans =
0 0 0
>>

Tuesday, March 2, 2010

[pymex] Python in Matlab

So I've been pretty busy on a few different things. One of those things happens to be pymex. I often need to extend Matlab to do something

To extend Matlab's capabilities it's necessary to write mex files in C/C++. Python is quick to code and it already has a bunch of available modules. With pymex a programmer can embed Python code inside of Matlab and avoid the whole mex file thing.

As an added benifit I also wrote a python module called 'matlab'. This module does two things. First, it provides a simple print function which prints to Matlab's command window (like mexPrintf). Second, it allows Python variables to be 'pushed' to Matlab.

matlab.mex_print(str, ...)
'''Like Pythons built-in print function, takes a variable
length of objects, converts them to strings using str(),
and prints the result to the Matlab command window.'''

matlab.push(varname, var, ...)
'''Using the Matlab function 'assignin', creates a Matlab
variable in the caller's scope from 'var' named 'varname'.
The 'varname' must be a valid Matlab variable name.
The 'var' must be a scalar; lists, tuples, and objects are
not supported yet.'''


Here's a sample script to show what pymex can do.

pyscript = sprintf([...
'import matlab\n', ...
'x = 7\n', ...
'for i in range(x):\n', ...
' matlab.mex_print(i)\n', ...
' matlab.push("i_%%d" %% i, i)\n', ...
'matlab.mex_print("demo complete!")\n', ...
]);

pymex(pyscript);