Create variables from xlsx-file.
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Soeren Friis Oestergaard Jensen
le 3 Fév 2017
Modifié(e) : Guillaume
le 6 Fév 2017
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?
Réponse acceptée
Carl
le 6 Fév 2017
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.
0 commentaires
Plus de réponses (1)
Guillaume
le 6 Fév 2017
Modifié(e) : Guillaume
le 6 Fév 2017
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.
0 commentaires
Voir également
Catégories
En savoir plus sur Spreadsheets dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!