MATLAB:替代使用'eval'来评估字符串 [英] MATLAB: Alternative to using 'eval' in order to evaluate string

查看:182
本文介绍了MATLAB:替代使用'eval'来评估字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个单元格数组中有一堆char数组,这些数组实际上代表了MATLAB结构的声明.像这样:

I have a bunch of char arrays within a cell array that actually represents the declaration of MATLAB structs. Something like this:

tmp{1} = 'testData.input = [1;2;3;4;5]'
tmp{2} = 'testData.output = [2;4;6;8;10]'

我需要执行这些命令",并最终创建相应的结构.我在for循环中使用eval函数,它可以正常工作.

I need to execute these "commands" and eventually create the respective struct. I am using the eval function within a for-loop and it works.

numEntries = numel(tmp);
for i = 1 : numEntries
    eval(tmp{i});
end

但是,这太慢了.我应该提到的是,真正的char数组非常大,实际上包含了3,000多个数字.同样,tmp单元阵列本身包含大约25,000个单元. 鉴于我无法更改输入数据,是否有一种提高性能的方法,即tmp只是从外部来源给出的?

However, this is painfully slow. I should mention that the real char arrays are very large, effectively containing more than 3,000 numbers. Also, the tmp cell array itself contains some 25,000 cells. Is there a way to improve performance given that I can't change the input data, i.e. tmp is simply given from an external source?

推荐答案

仅以您给出的2行为例,我无法测试它是否明显更快,但是当tmp成长.

I cannot test if it is significantly faster with only the 2 lines you gave as an example but I would expect this method to be faster when the number of elements of tmp grows.

想法是将tmp中包含的所有分配指令写入文本文件(实际上是.m文件),然后简单地执行.m文件.对于大量的行,我希望它比循环重复调用eval更快.

The idea is to write all the assignment instructions contained into tmp into a text file (an .m file actually), then simply execute the .m file. For large number of lines I would expect that to be way faster than having to invoque eval repeatedly in a loop.

因此,这里的示例tmp可以很好地工作,最终在工作区中使用结构testData.

So here goes, this works fine with your example tmp, you end up with the structure testData in your workspace.

%% Create an '.m' file containing all the assignment instructions from the cell array
tmpFile  = 'tmpFile2execute.m' ;
fidw = fopen( tmpFile , 'w' ) ;
fprintf(fidw,'%% Auto generated file\n'); % or any other header line you want, or none...
for i = 1 : numel(tmp) ;
    fprintf(fidw,'%s ;\n',tmp{i});
end
fclose(fidw) ;
% (optional) only to keep workspace tidy
clear i fidw tmpFile tmp 

%% Execute the file
tmpFile2execute ;


扩展这个想法,您可以将其设置为function而不是script,您可以在其中添加一些后期处理并将结果返回到变量中,而不是直接在工作空间中返回,但是您必须查看基数这个想法首先带来了速度上的改进.


Expanding on the idea you could make it a function instead of a script, where you could add some post processing and return the result in a variable instead of directly in the workspace but you have to see if the base idea brings any speed improvment first.

这篇关于MATLAB:替代使用'eval'来评估字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆