Importing a excel file with inconsistent row length, amount of columns, and blank cells.
Show older comments
Hello all,
I am trying use Matlab to load an excel file that has multiple matrices of different sizes that sometimes have blank cells in the middle of the matrix. I save this file as a .txt and when I load it in Matlab an error message states inconsistent row length. Is there a way to replace blank cells in excel with NaN? or is there a way to solve this within Matlab?
-Thanks
Accepted Answer
More Answers (1)
Matt Tearle
on 10 Mar 2011
You can read in a cell array of all Excel cells using xlsread:
[~,~,raw] = xlsread('file.xls');
You can also specify a range to read. Given a cell array where everything is either numeric or empty, here's a way to turn the blanks into NaNs:
x = {1,2,[];[],3,4;[],[],6}
idx = cellfun(@isempty,x);
x(idx) = num2cell(NaN)
cell2mat(x)
5 Comments
Walter Roberson
on 10 Mar 2011
Will that work on CSV files that have lines that have fewer columns than normal? If it will, then is that behaviour the same for Windows using COM to talk to Excel and for non-Windows systems that parse the file more manually ?
John Collette
on 10 Mar 2011
Walter Roberson
on 10 Mar 2011
John,
Could you confirm that some of the rows have fewer fields (not just fewer populated fields) ? e.g.,
Apple,,Nightshade,Tomato
Strawberry,Banana,Pecan
The missing field on the first line would not be difficult, but the second line only has 3 fields instead of 4 and that introduces complications. If we could be sure that such lines would instead be (e.g.)
Strawberry,Banana,Pecan,
then it would be easier.
John Collette
on 11 Mar 2011
John Collette
on 11 Mar 2011
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!