我有一个包含以下数据的单元格:
Tom Student
Jim Faculty
Clare Student
我想要做的是在前面添加另一列作为序列号。
1 Tom Student
2 Jim Faculty
3 Clare Student
有人可以给出一些建议吗?
答案 0 :(得分:11)
您将A
定义为:
>> A={'Tom', 'Student'; 'Jim', 'Faculty'; 'Clare', 'Student'}
A =
'Tom' 'Student'
'Jim' 'Faculty'
'Clare' 'Student'
添加列:
>> newCellCol = strsplit(num2str(1:size(A,1)))'
newCellCol =
'1'
'2'
'3'
>> A = [newCellCol A]
A =
'1' 'Tom' 'Student'
'2' 'Jim' 'Faculty'
'3' 'Clare' 'Student'
>>
对于第一列中的数字数组:
>> 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'
如Dan所述,您也可以使用num2cell(1:size(A,1))'
代替上面mat2cell
。
答案 1 :(得分:1)
不确定您的单元格阵列是如何组织的,但如果如下所示,您可以执行以下操作:
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'