Create variables from xlsx-file.

5 ビュー (過去 30 日間)
Soeren Friis Oestergaard Jensen
Soeren Friis Oestergaard Jensen 2017 年 2 月 3 日
編集済み: Guillaume 2017 年 2 月 6 日
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.

カテゴリ

Help Center および File ExchangeSpreadsheets についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by