8

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?

1
  • 1
    [{1;2;3}, data] where data is the cell array of strings. Commented Sep 6, 2014 at 7:23

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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'

3 Comments

Why not just a=num2cell(1:3)'; [a,A];?
@Dan Better, but it gives an error "Dimensions of matrices being concatenated are not consistent." I'm sure it could be fixed quickly, but I have to go now. No time to check. Thx.
I think that's because you have made A a cell array of cell arrays instead of a cell matrix like in the OP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.