File Exchange

image thumbnail

Cell 'Find And Replace'

version (734 Bytes) by Yoav Mor
Finds all occurrences of NaN in a cell array and replaces them.

1 Download

Updated 26 Apr 2006

No License

cellData=cellNaNReplace (cellData, replaceWith)

Accepts a cell array and a char/integer and replaces all occurrences of NaN in that cell array with the 'replaceWith' value. This is especially useful when using 'readfromexcel' or other excel importers since they sometimes put NaN instead of empty cells.

Example of usage:
a = num2cell([0 1 2 NaN 4]);
b = cellNaNReplace (a,'');

or, if you're dealing with excel spreadsheets, you can use:

Data = readfromexcel(File,'All');
Data = cellNaNReplace (Data,0);


Comments and Ratings (4)

best function ever!! Thanks a lot! I had so much truble and this is just great!

fan houjun


Arya Bolurfrushan


This is a great function but I get into this error constantly "??? Incorrect number of inputs.
On line 57 ==> cellData = cellfun(@cellrep, cellData, 'UniformOutput', false);"

Please help

Sebastian Walderich

Hi Yoav,

Good job, thanks for that! But maybe some annotations ;-)
For cell-arrays including numbers only, you can simply do something like this:
a = {1 2 NaN; 3 NaN 4; NaN 5 6};
a(isnan([a{:}])) = {-1}

Your script doesn't handle cell-arrays within cell-arrays, so I simplfied it to this:

function cellData = cellNaNReplace (cellData, replaceWith)
if nargin ~= 2
error(['function cellNaNReplace does not take ' nargin ' arguments']);
elseif ~iscell(cellData)
error(['first argument must be a cell array']);

cellData = cellfun(@cellrep, cellData, 'UniformOutput', false);

function value = cellrep(num)
if ~iscell(num) & isnan(num)
value = replaceWith; % the replaced value
value = num; % the original number back.

There's no need for your parameter-trick. Nested subfunctions can see their parents variables.

Again, thanks for the script!

MATLAB Release Compatibility
Created with R14SP3
Compatible with any release
Platform Compatibility
Windows macOS Linux

Inspired by: readfromexcel