Tuesday, May 17, 2011

Cell array to matrix in Matlab

Having used Matlab for machine learning work, I often face this problem. Typically while working with some classifier like "TreeBagger", the "eval()" function for computing labels of test data returns a cell array where each element is '1' or '-1'. The problem is that my original labels were numeric {1,-1}, so comparing these become a big problem especially if one is interested in things beyond accuracy.

Here is a simple technique to convert this cell array to a matrix. Say the original cell array is:
cellArr={'-1'; '-2'; '3' ;'6' ;'5'};
Now to convert this into a numeric array, all you have to do is:
This calls the function str2num for each element of the cell array and returns the resultant matrix in numeric format.

1 comment:

  1. A fellow IISc-ian pointed out cell2mat() for doing the same ... here's a discussion why the method outlined here works in more general cases ... https://profiles.google.com/bigyan.techie/posts/BKPCK8EGGNj#bigyan.techie/posts/BKPCK8EGGNj


I'd love to hear from you !