Reputation: 4899
I have an Excel sheet that contains the definitions of a structure including its content that I would like to import into MATLAB. For example, the definition in two Excel cells may look like this and is saved as a concatenated string:
testCase.expectedSolution.long = [1,2,3 ; 4,5,6 ; 7,8,9];
testCase.expectedSolution.short = [10,11,12 ; 13,14,15 ; 16,17,18];
I am using these definitions as expected solutions for unit tests in MATLAB. Right now, I am simply doing copy & paste from Excel into the MATLAB code in order to define the structure in MATLAB. However, I am wondering whether it is possible (and suitable) to import these strings into MATLAB. In reality, I have up to thousands of strings that will be generated from a VBA macro in Excel.
Upvotes: 2
Views: 182
Reputation: 2565
I created the Excel workbook shown in the image, named it Book1.xlsx
and saved it in my working directory.
Then I created the following MATLAB script which uses xlsread
to read the entire A column of the first sheet (Sheet1) and then uses eval
to execute the string contained in every cell, as if you would have typed every instruction manually in the Command Window:
filename = 'Book1.xlsx';
sheet = 1;
xlRange = 'A:A';
[~, txt, ~] = xlsread(filename, sheet, xlRange);
for i = 1:size(txt, 1)
eval(txt{i});
end
This is the output:
>> testCase.expectedSolution
ans =
long: [3x3 double]
short: [3x3 double]
Be careful with eval
because:
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.
I strongly suggest you to read TUTORIAL: Why Variables Should Not Be Named Dynamically (eval) so you understand the implications of using eval
.
Quoting 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.
Upvotes: 1
Reputation: 14547
You could use readtable
or importdata
.
xlsread
or uiimport
might work too, see this link for available options.
Upvotes: 0