Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing elements from a cell array in MATLAB

I have a cell array as shown below:

a = {[1 2 3] [5 3 6] [9 1 3]};

Now I want to remove the 1s from every array in a that contains 1 so that the output is as shown

a = {[2 3] [5 3 6] [9 3]};

I know the indices of arrays in cell array 'a' which contain 1. This can be done using for loop and a temporary variable, but this is taking a lot of time (I want to perform the operation on a cell array of size something like 1x100000. The one above is just for an example)

I want to know if there is any direct method that can do this quickly.

like image 674
akki Avatar asked May 18 '26 01:05

akki


2 Answers

Pretty much anything is going to be slow with that large of a cell array. You could try to do this with cellfun but it's not necessarily guaranteed to be any faster than a for loop.

a = cellfun(@(x)x(x ~= 1), a, 'UniformOutput', false);

%   a{1} =
%        2     3
%   a{2} =
%        5     3     6
%   a{3} =
%        9     3
like image 68
Suever Avatar answered May 20 '26 20:05

Suever


As already commented by Suever, because you are using a cell array and it is a dynamic container, you don't have a choice but to iterate through each cell if you want to modify the contents. Just to be self-contained, here is the for loop approach to do things:

for ii = 1 : numel(a)
    a{ii} = a{ii}(a{ii} ~= 1);
end

This may be faster as it doesn't undergo the overhead of cellfun. The code above accesses the vector in each cell and extracts out those values that are not equal to 1 and overwrites the corresponding cell with this new vector.

Using your example:

a = {[1 2 3] [5 3 6] [9 1 3]};

We get:

>> format compact; celldisp(a)
a{1} =
     2     3
a{2} =
     5     3     6
a{3} =
     9     3
like image 34
rayryeng Avatar answered May 20 '26 20:05

rayryeng