sunny
sunny

Reputation: 51

Convert matrix to cell and replace NaN with '-'

I have a matrix A

A = [nan nan 1 0 nan]

How do I convert matrix A to cell, and replace nan with '-', so a new B cell array will look like this:

B = {'-' '-' 1 0 '-'}

I tried

A = mat2cell(A);

or

A = num2str(A);

then

A(cellfun(@isNaN,A,'uniformoutput',false)) = {'-'};

This is not working.

Upvotes: 1

Views: 379

Answers (3)

Wolfie
Wolfie

Reputation: 30046

You could pair two of your attempts, note that you do want 'UniformOutput' from the cellfun because you need a logical array.

A = num2cell(A);
A(cellfun(@isnan,A)) = {'-'};

Alternatively you could just use a loop...

B = cell( size( A ) );
idx = isnan( A );
for ii = 1:numel(A)
    if idx(ii)
        B{ii} = '-';
    else
        B{ii} = A(ii);
    end
end

This might seem obtuse, but if you're struggling with the correct implementation of mat2cell/cellfun/etc, then you can guarantee code written with those functions will be harder to maintain for yourself and others! At least the loop is explicit, and not necessarily slow these days (although if you're storing numeric data in mixed type cell arrays then I have to assume performance isn't paramount anyway).

Upvotes: 2

HansHirse
HansHirse

Reputation: 18905

Your idea using mat2cell is good, maybe the usage just isn't clear!? You could also use num2cell, which seems a bit more easier to use. Additionally, indexing with logical values also works with cell arrays, which might be more efficient than cellfun and similar:

A = [nan nan 1 0 nan]

B = num2cell(A);
B(isnan(A)) = {'-'}

Output:

A =
   NaN   NaN     1     0   NaN

B =
{
  [1,1] = -
  [1,2] = -
  [1,3] =  1
  [1,4] = 0
  [1,5] = -
}

Hope that helps!

Upvotes: 3

ThomasIsCoding
ThomasIsCoding

Reputation: 101343

I think you can try num2cell

B = num2cell(A);
B(cellfun(@isnan,B)) = {"_"};

which gives

>> B
B =
{
  [1,1] = _
  [1,2] = _
  [1,3] =  1
  [1,4] = 0
  [1,5] = _
}

Upvotes: 1

Related Questions