Andre Marin
Andre Marin

Reputation: 542

For Matlab, Import data from xlsx, how to get 1st row as variable name, and rest of the column as data for variable name

In my excel file. The very first row in each column is a string. The rest of the column is data for that string, i.e

'time' 
1
2
3
4

I want to take the first row in excel, and make that the variable name in Matlab, and the rest of the column data is numerical data for that variable. So in Matlab, time would be a column vector of numbers 1, 2 ,3 ,4.

I can't get this to work.

Upvotes: 2

Views: 6055

Answers (1)

Shai
Shai

Reputation: 114796

how about

[val nms] = xlsread( xlsFileName );
assert( size(val,2) == size(nms,2), 'mismatch number of columns and number of names');
for ci=1:size(val,2)
    eval( [ nms{ci}, ' = val(:,ci);' ] ); % name the column
end

What makes this work:

  1. This code calls xlsread with two output variables. This way xlsread puts the numeric data into the first variable, and text data into the second. See xlsread doc for more info.

  2. Using eval to assign values to variable (time) which name is stored in another variable (nms{1}). The argument of the eval commands is a string time = val(:,1);, which the Matlab command that assigns the values of the first column of data (val(:,1)) to a new variable named time.

Upvotes: 2

Related Questions