Create variables from xlsx-file.

1 次查看(过去 30 天)
I have a MATLAB script where I load data from an xlsx-file, using 'xlsread(filename,sheet,xlRange)'. However this gives me the data in cells. I want to turn these into variables. I tried a loop using cell2mat but this didn't work:
[subsetA,y] = xlsread(filename,sheet,xlRange);
N = length(y(:,1));
y1=zeros(1,N);
for i=1:N
y1(i) = y{i,1};
end
Doesn't work.... Any suggestions?

采纳的回答

Carl
Carl 2017-2-6
See the documentation on "xlsread" here:
You can see that the second returned value (in your case, "y") is the text fields in a cell array. When you index with the {} brackets, what gets returned is a char array representation of that text. In your code, you are trying to set this char array into a numerical value (y1 is a double array). The data types are conflicting, so this does not work. I would recommend keeping the cell array representation returned by xlsread, as this is the easiest way to store/access strings that differ in length.
I would also like to second Stephen's comment. If it's true that you would like to create variables named after strings in your spreadsheet, I would highly recommend rethinking the design of your code. Stephen's link gives a great tutorial on alternatives.

更多回答(1 个)

Guillaume
Guillaume 2017-2-6
编辑:Guillaume 2017-2-6
Matlab has had readtable for over two years now. It's a lot more powerful than xlsread, can read the header of your excel data if there is one, and nicely create variables as columns of a table rather than a cumbersome cell array. Ditch xlsread (assuming you're not stuck on an ancient version).
mytable = xlsread('someexcelfile.xlsx');
%if column has header 'Total':
mytable.Total %return values of column 'Total'
easy peasy.

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by