How to add NaN to a matrix with few empty elements?
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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.
0 comentarios
Respuestas (2)
Walter Roberson
el 27 de Mayo de 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 comentario
Salaheddin Hosseinzadeh
el 27 de Mayo de 2015
Editada: Salaheddin Hosseinzadeh
el 27 de Mayo de 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!
1 comentario
Ver también
Categorías
Más información sobre Data Type Conversion en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!