How to read specific columns into an array(or a table) from a spreadsheet in matlab?

95 views (last 30 days)
I just started to learn programming in matlab. The problem I encounter is how to read specific columns from a spreadsheet? I read the documentation and know how to read a rectangle from a spreadsheet, but what if I just want to read some specific columns which are not near each other? For example, there are A,B,C,D,E,F,G columns in a spreadsheet, and I just want B, D, F columns out of it. How to do that? Thanks!

Accepted Answer

dpb
dpb on 28 Jan 2016
AFAIK, "no can do" with xlsread; it can only pass a single range argument. In Matlab, it's probably simplest to simply import the full sheet then just keep the columns you want (or, conversely, clear the unwanted columns by setting to []).
The syntax for a single column is 'A:A' or '5:5' for column A or row 5, respectively. Unfortunately,
x=xlsread('file.xls','A:A,D:D,F:F')
doesn't error, it just returns column A, ignoring other inputs even though that is syntax which internally inside Excel you could write something like =SUM(A:A,D:D,F:F) in B1, say.
For your specific case,
x=xlsread('file.xls','B:F'); % subgroup
x=x(:,1:2:end); % save columns 1,3,5 which originally were B,D,F
This illustrates some other features of Matlab indexing expressions as well.
In reality, I'd probably write
x=xlsread('file.xls'); % just read the sheet
x= x(:,['B' 'D' 'F']-'@'); % save columns B,D,F
which illustrates yet another feature that you can also do arithmetic on characters. It just so happens I've been around the block enough times that I happen to remember that '@' precedes upper-case 'A' in the ASCII collating sequence w/o having to look it up or compute it. That comes from being far too old, basically... :)
Or, of course you can write if it's simpler indexing
x=xlsread('file.xls'); % just read the sheet
x(:,['A':2:'G']-'@')=[]; % clear columns A,C,E,...
Experiment with the above indexing expressions at the command line to see what they do and how...

More Answers (0)

Categories

Find more on Data Import from MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!