Cedric Zoppolo
Cedric Zoppolo

Reputation: 4743

How to create a sub-cell from a cell array in Matlab?

Lets say I have following cell array data in Matlab:

>> data = {'first', 1; 'second', 2; 'third', 3}

data = 

    'first'     [1]
    'second'    [2]
    'third'     [3]

Then I want to create a new cell array which has only the first column data. I tried the following but got only the first value instead.

>> column_1 = data{:,1}

column_1 =

first

But what I would like to get as output is:

>> column_1 = {'first';'second';'third'}

column_1 = 

    'first'
    'second'
    'third'

How can I create a sub-cell from first column of data cell array?

Upvotes: 0

Views: 1923

Answers (1)

Tommaso Belluzzo
Tommaso Belluzzo

Reputation: 23675

You have to use round parentheses indexing instead of curly braces indexing, like this:

data(:,1)

Output:

ans =
      3×1 cell array
      'first'
      'second'
      'third'

Basically, the purpose of curly braces is to retrieve the underlying content of cells and present a different behavior. For extracting subsets of cells you need to use round parentheses. For more details, refer to this page of the official Matlab documentation.

Upvotes: 2

Related Questions