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

9 vues (au cours des 30 derniers jours)
Meera
Meera le 27 Mai 2015
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.

Réponses (2)

Walter Roberson
Walter Roberson le 27 Mai 2015
Leave the elements empty, whether that is by using [] or ''. str2double() that. The result will have NaN everywhere there was [] or '' to convert.
  1 commentaire
Lexington Stoyell
Lexington Stoyell le 6 Mar 2018
What do you mean by this? How do you do this?

Connectez-vous pour commenter.


Salaheddin Hosseinzadeh
Salaheddin Hosseinzadeh le 27 Mai 2015
Modifié(e) : Salaheddin Hosseinzadeh le 27 Mai 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!

Catégories

En savoir plus sur Data Type Conversion dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by