Importing a excel file with inconsistent row length, amount of columns, and blank cells.
Afficher commentaires plus anciens
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
Réponse acceptée
Plus de réponses (1)
Matt Tearle
le 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 commentaires
Walter Roberson
le 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
le 10 Mar 2011
Walter Roberson
le 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
le 11 Mar 2011
John Collette
le 11 Mar 2011
Catégories
En savoir plus sur Spreadsheets dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!