Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace empty cells with logical 0's before cell2mat in MATLAB

I have an array of empty cells and ones that I want to convert to a logical array, where the empty cells are zeros. When I use cell2mat, the empty cells are ignored, and I end up with a matrix of solely 1's, with no reference to the previous index they held. Is there a way to perform this operation without using loops?

Example code:

for n=1:5              %generate sample cell array
    mycellarray{n}=1;
end
mycellarray{2}=[]      %remove one value for testing

Things I've tried:

mylogicalarray=logical(cell2mat(mycellarray));

which results in [1,1,1,1], not [1,0,1,1,1].

for n=1:length(mycellarray)
    if isempty(mycellarray{n})
       mycellarray{n}=0;
    end
end
mylogicalarray=logical(cell2mat(mycellarray));

which works, but uses loops.

like image 592
Doresoom Avatar asked Apr 12 '10 17:04

Doresoom


People also ask

How do you empty a cell in Matlab?

Like all MATLAB® arrays, cell arrays are rectangular, with the same number of cells in each row. myCell is a 2-by-3 cell array. You also can use the {} operator to create an empty 0-by-0 cell array. To add values to a cell array over time or in a loop, create an empty N -dimensional array using the cell function.

How do I read a cell in Matlab?

Access the contents of cells--the numbers, text, or other data within the cells--by indexing with curly braces. For example, to access the contents of the last cell of C , use curly braces. last is a numeric variable of type double , because the cell contains a double value.


1 Answers

If you know your cell array is only going to contain ones and [] (which represent your zeroes), you can just use the function cellfun to get a logical index of the empty cells, then negate the index vector:

mylogicalarray = ~cellfun(@isempty, mycellarray);
% Or the faster option (see comments)...
mylogicalarray = ~cellfun('isempty', mycellarray);

If your cells could still contain zero values (not just []), you could replace the empty cells with 0 by first using the function cellfun to find an index for the empty cells:

emptyIndex = cellfun('isempty', mycellarray);     % Find indices of empty cells
mycellarray(emptyIndex) = {0};                    % Fill empty cells with 0
mylogicalarray = logical(cell2mat(mycellarray));  % Convert the cell array
like image 82
gnovice Avatar answered Oct 23 '22 09:10

gnovice