Clear Filters
Clear Filters

How to add NaN to a matrix with few empty elements?

8 views (last 30 days)
Hello,
A cell with 50000 elements is having few empty elements.
x = {'1' '25' '55' '24'.....};
There is an empty element between '55' and '24'. I wanted to fill the empty elements with 'NaN'. 'NaN' is a double but the elements in cell X are 'char'. At first I added 'NaN' as follows.
x(cellfun('isempty',x)) = NaN;
This code is adding NaN to cell x. But later when I am converting 'char of cell x to double' it is giving me an error. Because the cell x have char and NaN which is a double. So it is difficult to convert.
str2double(cell2mat(x));
So, can you please give me an idea how to add 'NaN' to cell and then convert the char in cell to double.

Answers (2)

Walter Roberson
Walter Roberson on 27 May 2015
Leave the elements empty, whether that is by using [] or ''. str2double() that. The result will have NaN everywhere there was [] or '' to convert.

Salaheddin Hosseinzadeh
Salaheddin Hosseinzadeh on 27 May 2015
Edited: Salaheddin Hosseinzadeh on 27 May 2015
Hi,
I don't think there is an easy way to do this, if you convert them at once you will end up with
x = 12555....
and this is a character which if you then convert to double it will be one single number! On the other hand if you wanna use cell2mat all your data types should be the same, you can't have double (nan) and characters in the same cell and get it converted at once!
A possible solution is to make a for loop to go through each and every element. Simply convert them to double and put them in an array, if you encountered any empty elements in your cell then put nan in your array.
Roughly something like this
outputArray = zeros(1,numel(x));
for i = 1:numel(x)
if isempty(x{i})
outputArray(i) = nan;
else
outputArray(i) = str2double(x{i});
end
end
Something like this, Please don't copy paste cuz its not tested.
Good luck!

Categories

Find more on Data Type Conversion 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!