excel - 将矩阵定义从 Excel 导入 MATLAB

标签 excel matlab import

我有一个 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并将其保存在我的工作目录中。

Excel workbook

然后我创建了以下使用 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 are system(''rm -r /''); a? Something bad, that's what.

关于excel - 将矩阵定义从 Excel 导入 MATLAB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42202486/

相关文章:

string - 在字符串中查找特定数字?

python - 如何解决 Python 中的函数逼近任务?

mysql - 将 CSV 文件导入 MySQL 表,仅导入第一行

r - 如何将 Qualtrics 数据(以 csv 格式)导入 R

excel - VBA ActiveX 控件的大小随着远程桌面连接的增加而增大

Excel If 语句

vba - 是否可以撤消宏操作?

c++ - 在 C++ 中使用 startMATLAB 并在 r2017b 中使用 "MatlabEngine.hpp"时发出问题

Matlab:如何在没有 Tab 的情况下激活自动完成?

datetime - 如何将日期时间数据导入到sqlite3?