Jamee Lin
Jamee Lin

Reputation: 35

How do I remove a certain column from matrices in a cell array in MATLAB?

If I have a cell array containing few matrices in it. Each matrix has different row numbers but same column numbers.

C{1} = [30x4 double] C{2} = [25x4 double] C{3} = [32x4 double] ...etc

If I want to remove the first and the third columns in each matrix, what should I do?

So the cell array will become:

new_C{1} = [30x2 double] new_C{2} = [25x2 double] new_C{3} = [32x2 double]

where those two columns in new_C are from the second and the fourth columns in the cell array C.

Upvotes: 3

Views: 124

Answers (1)

zeeMonkeez
zeeMonkeez

Reputation: 5157

I assume you have tried the obvious solution using a for loop. Another way would be using cellfun, combined with logical indexing:

columns = false(1, 4);
columns([2, 4]) = true;
D = cellfun(@(m)m(:,columns), C, 'UniformOutput', 0)

first, we build an index vector for the columns. Then we use cellfun to apply the indexing to every element in the cell array. We use 'UniformOutput', 0, because we want to obtain another cell array (and the results of the indexing operation are not scalar).

Upvotes: 1

Related Questions