Find the index of zero in cell and put it as empty

A={[45;101],[2;7],[5;8],0,0};
A(cell2mat(A)==0)={[]}; % I want to find zero and put in empty
A should be
A={[45;101],[2;7],[5;8],[],[]};

 Accepted Answer

A(cellfun(@(x) isequal(x, 0), A)) = {[]}; %replace any cell whose content is the scalar 0 by empty
is one way.
edit: fixed code.

6 Comments

I have this error
Unable to perform assignment because the left and right sides have a different number of elements.
Does not work due to the sizes of the left and right arrays can differ. The working version can be
A(cellfun(@(x) isequal(x, 0), A)) = cell(size(A(cellfun(@(x) isequal(x, 0), A))));
Can be optimized via precomputing cellfun...
Yes, I should have tested the code. Either
[A{cellfun(@(x) isequal(x, 0), A)}] = deal([]); %replace any cell whose content is the scalar 0 by empty
which is a bit convoluted or
toreplace = cellfun(@(x) isequal(x, 0), A);
A(toreplace) = cell(1, nnz(toreplace));
Actually the original idea is fine, it just needs a scalar cell array on the RHS:
>> A = {[45;101],[2;7],[5;8],0,0}
A =
[2x1 double] [2x1 double] [2x1 double] [0] [0]
>> A(cellfun(@(x)isequal(x,0), A)) = {[]} % SCALAR CELL ARRAY
A =
[2x1 double] [2x1 double] [2x1 double] [] []
When allocating to the LHS the RHS can always be a scalar, and this applies to cell array just like any other array type. Instead of making this more complex, all that is required is the scalar cell array {[]} rather than the empty cell array {}.
Do'h! I knew this was simple. Thanks, Stephen. For some reason, I had it in my head that {} and {[]} were the same thing.

Sign in to comment.

More Answers (0)

Categories

Asked:

NA
on 7 Jan 2020

Commented:

NA
on 8 Jan 2020

Community Treasure Hunt

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

Start Hunting!