我有一个带有数学表达式的单元格,我想将其转换为数值数组。它看起来如下:
a = {};
a{1,1} = '0.55';
a{2,1} = '0.25 + 0.50';
现在我想接收结果(但最好没有for循环):
b(1) = 0.55;
b(2) = 0.75;
我如何有效地做到这一点?
答案 0 :(得分:2)
b = cellfun(@eval,a);
将创建一个与单元格数组b
相同大小的数组a
,每个值都是对单元格数组中相应字符串的求值。
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
另一种选择是制作一个大字符串表达式,这样由于eval
内部循环的作用,cellfun
仅被调用一次,而不是多次调用。这不太安全,因为单元格数组a
中的异常值可能会导致代码崩溃,而在上面的代码中可能仅产生 NaN 。
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