b = cellfun(@eval,a);
will create an array b
of the same size as cell array a
, with each value the evaluation of the corresponding string in the cell array.
a = {};
a{1,1} = '0.55';
a{2,1} = '0.25 + 0.50';
a=repmat(a,1000,20); %Make it big for performance evaluation
tic
b1 = cellfun(@eval,a);
toc %0.662187 seconds
Another option is to make a big string expression so that eval
is called only once rather than several times due to cellfun
internal loop. This is less safe as abnormal values in the cell array a
will likely cause the code to crash, while it may simply produce NaN in the code above.
tic
% add a comma separator after each value
strCell = cellfun(@(x) [x ','],transpose(a),'uniformoutput',false);
% add a semicolon separator at the end of each row
strCell(end,:) = cellfun(@(x) [x(1:end-1) ';'], strCell(end,:), 'uniformoutput',false);
% remove the last separator
strCell{end}=strCell{end}(1,end-1);
% evaluate the line
b2=eval(['[' strCell{:} ']']);
toc %0.313738 seconds but sometimes more than 1 seconds