Home > front end >  Matlab: read multiple columns from an excel spreadsheet by using xlsread
Matlab: read multiple columns from an excel spreadsheet by using xlsread

Time:03-31

I have an Excel sheet with 300 columns, from which I just need several ranges. In a normal case I use the "import data" app. But this time it is not possible, because some of the strings are double. I just want to read the first row and from this, several columns (all strings). Just as an example: I have a first row with strings like this:

x= ["'[23Na] '" ,  "'[24Mg] '" ,  "'[25Mg] '" ,  "'[26Mg] '" , "'[26Mg]  '" ,  "'[27Al] '" , "'C2H3 '" , "'[28Si] '"] 

And now I just want to have A1:B1 and E1:F1. How do I use here xlsread with several ranges to end with a string like this:

x= ["'[23Na] '" ,  "'[24Mg] '" , "'[26Mg]  '" ,  "'[27Al] '"] 

I am grateful for every hint.

CodePudding user response:

I hope my answer will not be downvoted for trying to convince you to approach the problem differently. :-)

The problem is two-fold:

Problem 1. xlsread() doesn't support disjoint ranges. This implies that the only way to read disjoint ranges is to call xlsread() for each contiguous range, and then combine the results, e.g:

FNAME   = 'Book1.xlsx';
SHNAME  = 'Sheet1';
RANGES  = {'A1:B1', 'E1:F1'};
READFUN = @(rg) xlsread(FNAME, SHNAME, rg);

[~,~,raw] = cellfun(READFUN, RANGES, 'UniformOutput', 0);

x = [raw{:}];    % [!] depending on RANGES, this might fail

Problem 2. Every time is called, xlsread() (a) instantiates a COM server for Excel, (b) opens the file, (c) reads the data, (d) closes the file, and (e) cleans up the COM server. Steps (a), (b), (d), and (e) add A LOT OF OVERHEAD for reading just one small range at step (c).

Approach. I suggest to you to get all the raw data in one read: it will be faster and (funnily enough) less memory-intensive. You'll get a cell matrix with all the data in the sheet, but then you can process the data at your leisure, using the way-more-powerful indexing capabilities of MATLAB (compared to Excel's ranges):

[~,~,raw] = xlsread(FNAME, SHNAME);  % all the data, numeric or text

x = raw(1, [1,2,5,6]);

... continue processing here
  • Related