我有一个 Excel 工作表,其中包含结构的定义,包括我想导入 MATLAB 的内容。例如,两个 Excel 单元格中的定义可能如下所示,并保存为串联字符串:
testCase.expectedSolution.long = [1,2,3 ; 4,5,6 ; 7,8,9];
testCase.expectedSolution.short = [10,11,12 ; 13,14,15 ; 16,17,18];
我将这些定义用作 MATLAB 中单元测试的预期解决方案。现在,我只是将 Excel 中的复制粘贴到 MATLAB 代码中,以便在 MATLAB 中定义结构。但是,我想知道是否可以(并且合适)将这些字符串导入 MATLAB。实际上,我有多达数千个字符串,这些字符串将从 Excel 中的 VBA 宏生成。
最佳答案
我创建了如图所示的 Excel 工作簿,将其命名为 Book1.xlsx
并将其保存在我的工作目录中。
然后我创建了以下使用 xlsread
的 MATLAB 脚本读取第一张表 (Sheet1) 的整个 A 列,然后使用 eval
执行每个单元格中包含的字符串,就像您在命令行窗口中手动键入每条指令一样:
filename = 'Book1.xlsx';
sheet = 1;
xlRange = 'A:A';
[~, txt, ~] = xlsread(filename, sheet, xlRange);
for i = 1:size(txt, 1)
eval(txt{i});
end
这是输出:
>> testCase.expectedSolution
ans =
long: [3x3 double]
short: [3x3 double]
小心
eval
因为:Many common uses of the
eval
function are less efficient and are more difficult to read and debug than other MATLAB functions and language constructs. For more information, see Alternatives to the eval Function.
我强烈建议您阅读TUTORIAL: Why Variables Should Not Be Named Dynamically (eval)让您了解使用
eval
的含义.报价 Sam Robert's answer :
eval
is even a security risk - what happens if the user types in a string where the selected characters aresystem(''rm -r /''); a
? Something bad, that's what.
关于excel - 将矩阵定义从 Excel 导入 MATLAB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42202486/