Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding column to cell array

Tags:

matlab

I have a cell that has the following data:

Tom     Student
Jim     Faculty     
Clare   Student

What I want to do is add in another column in front to be a serial number.

1   Tom     Student
2   Jim     Faculty     
3   Clare   Student

Could someone give some advise please?

like image 400
Lionel Koh Avatar asked Oct 30 '13 04:10

Lionel Koh


2 Answers

You have A defined as:

>> A={'Tom', 'Student'; 'Jim', 'Faculty'; 'Clare', 'Student'}

A = 

    'Tom'      'Student'
    'Jim'      'Faculty'
    'Clare'    'Student'

To add a column:

>> newCellCol = strsplit(num2str(1:size(A,1)))'

newCellCol = 

    '1'
    '2'
    '3'

>> A = [newCellCol A]

A = 

    '1'    'Tom'      'Student'
    '2'    'Jim'      'Faculty'
    '3'    'Clare'    'Student'

>> 

For numeric arrays in the first column instead:

>> newCellCol = mat2cell(1:size(A,1),1,ones(1,size(A,1)))';
>> A = [newCellCol A]

A = 

    [1]    'Tom'      'Student'
    [2]    'Jim'      'Faculty'
    [3]    'Clare'    'Student'

You can also use num2cell(1:size(A,1))' in place of mat2cell above, as noted by Dan.

like image 170
chappjc Avatar answered Oct 16 '22 16:10

chappjc


Not sure exactly how your cell array is organized, but if like below, you can do as follows:

A={{'Tom', 'Student'}, ...
    {'Jim', 'Faculty'}, ...
    {'Clare', 'Student'}};


sizeA = size(A,2);

for i = 1:sizeA
    A{i} = [i, A{i}]
end

% alternatively, instead of a for loop, you can use cellfun
% A = cellfun(@(x, i)[i x], A, num2cell(1:size(A, 2)), 'UniformOutput',0)

A{1}
A{2}
A{3}

ans = 

    [1]    'Tom'    'Student'


ans = 

    [2]    'Jim'    'Faculty'


ans = 

    [3]    'Clare'    'Student'
like image 27
Marcin Avatar answered Oct 16 '22 14:10

Marcin