zesy
zesy

Reputation: 481

Matlab xlsread: force empty cells to be read as NaN

I need to import data from a square region (10 by 10 cells) on an Excel sheet into Matlab.

All data in the region are numerical, but some outer rows and columns of the region are empty.

In Matlab I still want to have a 10 by 10 matrix of doubles with NaNs in places where there are empty cells in Excel (also in outer rows and columns).

If I use xlsread then empty outer rows and columns are automatically truncated.

Needless to say that all should be done automatically without the knowledge how many empty outer rows and columns are there.

How can I do this?

Upvotes: 0

Views: 3397

Answers (1)

Christian S.
Christian S.

Reputation: 982

Let's say your 10 by 10 spreadsheet's first row and column and last row and column are empty (like this). Using:

[num,txt,raw] = xlsread('myfile.xlsx',1,'A1:J10'); % Read input.

will return:

num   8x8 double
txt   0x0 cell
raw   10x10 cell

In num, non-scalar leading rows and columns are automatically truncated, while in txt any numerical values are omitted. However, raw contains all information, so it can be used to extract the numerical values:

raw(cellfun(@ischar,raw)) = {NaN}; % Set non-scalar values to missing.
A = cell2mat(raw); % Convert to matrix.

Upvotes: 0

Related Questions