필터 지우기
필터 지우기

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

조회 수: 7 (최근 30일)
Meera
Meera 2015년 5월 27일
댓글: Lexington Stoyell 2018년 3월 6일
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.

답변 (2개)

Walter Roberson
Walter Roberson 2015년 5월 27일
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 2015년 5월 27일
편집: Salaheddin Hosseinzadeh 2015년 5월 27일
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!

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by