How to extract certain Excel columns?

174 views (last 30 days)
Lexington Stoyell
Lexington Stoyell on 16 Feb 2018
Answered: aderajew asayhe on 15 May 2019
I would like to extract columns based on their name (the first row of the column). These columns are randomly ordered.

Answers (3)

Matías Nomboly
Matías Nomboly on 16 Feb 2018
Edited: Matías Nomboly on 16 Feb 2018
Best quick thing I can think of is to use read table and then use MATLAB tables to classify items. Don't know about the efficiency of it, but it should work:
A=readtable('yourexcelfile.xlsx');
A then behaves as a cell structure, and thus you can use the function find(ismember())
coln=find(ismember(A(1,:),'yourstring'));
This returns the number of the column of the string that you are searching for Afterwards, you can recover your column by:
Anew=A(:,coln);
Hope this helps!
  3 Comments
Matías Nomboly
Matías Nomboly on 16 Feb 2018
OK, lets try this>
A=readtable('yourexcelfile.xlsx');
A=table2array(A);
coln=find(ismember(A(1,:),'yourstring'));
Anew=A(:,coln);
Guillaume
Guillaume on 16 Feb 2018
ismember is a bit overkill here. find(strcmp(x, 'yourstring') would produce the same result faster.
The main issue here is that the x should not be A(1, :) since row headers are not stored in the table values. They're used a variable nams and can be accessed through A.Properties.VariableNames if needed.
However, the whole thing is overkill, you can access the column by its name directly. That's the whole point of tables.

Sign in to comment.


Guillaume
Guillaume on 16 Feb 2018
Edited: Guillaume on 16 Feb 2018
Using readtable is indeed the right way to do it. By default, readtable should read the first row as variable names. If it doesn't then you can force it with:
t = readtable(yourfile, 'ReadVariableNames', true);
Be aware that matlab may have to change the column name slightly to make it a valid variable name (this is the warning you see), so you may have to adjust your search term if it's not a valid variable name.
You can then access the column that interest you very simply with:
t.yourcolumnname
e.g. if you're looking for a column whose header in excel is MeanValue simply do:
t.MeanValue
to get that column content. However, as said if the column header is Mean Value which is not a valid matlab variable name, then most likely you'd access that column with
t.Mean_Value
I recommend that you learn more about tables. They're very useful when reading excel files.

aderajew asayhe
aderajew asayhe on 15 May 2019
To whom may it concter,
Igot the file of matlab, it's run well... but i got a question how can do diviual into weekly profiling, monthly and yearly. to do from this matlab codes.
i help please.

Tags

Community Treasure Hunt

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

Start Hunting!