フィルターのクリア

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.
  1 件のコメント
Lexington Stoyell
Lexington Stoyell 2018 年 3 月 6 日
What do you mean by this? How do you do this?

サインインしてコメントする。


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!
  1 件のコメント
Salaheddin Hosseinzadeh
Salaheddin Hosseinzadeh 2015 年 5 月 27 日
It's tested and it works just fine!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by