フィルターのクリア

Remove NaN from doubles within a cell array

3 ビュー (過去 30 日間)
Jonathan Soucy
Jonathan Soucy 2017 年 7 月 7 日
回答済み: Pruthvi G 2020 年 3 月 12 日
For example, how would I get this:
ab = {[1 2 NaN 3 4];[1 3 4 NaN 5 6 7 NaN]}
to output
ab = {[1 2 3 4];[1 3 4 5 6 7]}
I've tried
ab(cellfun(@(x) all(isnan(x)),ab)) = []
but it doesn't work
  1 件のコメント
Pruthvi G
Pruthvi G 2020 年 3 月 12 日
ab(cellfun(@(cell) any(isnan(cell(:))),ab))={''};

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

採用された回答

Star Strider
Star Strider 2017 年 7 月 7 日
Try this:
ab = {[1 2 NaN 3 4];[1 3 4 NaN 5 6 7 NaN]};
Output = cellfun(@(x) x(isfinite(x)), ab, 'UniformOutput',false);
Out1 = Output{1} % Display Output (Delete)
Out2 = Output{2} % Display Output (Delete)
Out1 =
1 2 3 4
Out2 =
1 3 4 5 6 7
  1 件のコメント
Walter Roberson
Walter Roberson 2017 年 7 月 7 日
Note: isfinite is not the same as ~isnan() in that isfinite excludes +inf and -inf

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

その他の回答 (3 件)

Geoff Hayes
Geoff Hayes 2017 年 7 月 7 日
Jonathan - remember that the output of cellfun will be a cell array, so the code that you have above will work i.e. using a cell array as the indices into ab. Try defining a function that will do this for you, creating a function named removeNaNs and saving it to a file named removeNaNs.m
function [ab] = removeNaNs(ab)
ab = cellfun(@(x)removeNaNsPriv(x), ab, 'UniformOutput', false);
function [z] = removeNaNsPriv(z)
z(isnan(z)) = [];
We use the second function (saved within the removeNaNs.m file) as a "helper" function to remove the NaNs from an array. From the command line, you would call this code as
>> ab = {[1 2 NaN 3 4];[1 3 4 NaN 5 6 7 NaN]};
>> removeNaNs(ab)

Walter Roberson
Walter Roberson 2017 年 7 月 7 日
編集済み: Walter Roberson 2017 年 7 月 7 日
result = cellfun(@(M) M(~isnan(M)), ab, 'Uniform', 0)

Pruthvi G
Pruthvi G 2020 年 3 月 12 日
ab(cellfun(@(cell) any(isnan(cell(:))),ab))={''};

カテゴリ

Help Center および File ExchangeNaNs についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by