Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top