How can I create a new column counting the number of rows of a table?

14 views (last 30 days)
I have a 100x2 table, named t. I would like to add a third column which simply count the number of items of the table - that is an Index which I can print with the other columns. The original table looks like this:
To add an indexing column in R I would probably do a very simple operation like this: df$index <- 1:nrow(df).
What is the easiest solution in Matlab? Actually I am able to obtain what I want (see image below), but the code I use is really horrible...
%create new empty index column, the same size as table t
t.index=zeros(size(t, 1), 1)
%change column order, so that t is the first column
t = t(:,[3 1:2]);
%number index column
x=[]
index=0
for i=1:size(t, 1)
index=index+1
x(end+1) = index
end
t.index=x'
  2 Comments
Emanuele Cappella
Emanuele Cappella on 13 Nov 2017
You're right, I did not explain myself well enough. Please see the edited question, which I hope is clearer

Sign in to comment.

Accepted Answer

Steven Lord
Steven Lord on 13 Nov 2017
Edited: Steven Lord on 13 Nov 2017
The command you need is very similar to the R command you posted.
% Build a sample table
t = table(["call"; "free"; "txt"; "text"; "mobil"; "claim"], randi(100, 6, 1), ...
'VariableNames', {'Word', 'Count'})
% Add a new variable to the table.
% Use the height function to ensure it's the correct height
t.index = (1:height(t)).'
% If you want the index variable to be displayed first,
% reorder the columns using indexing
t = t(:, [3 1 2])

More Answers (1)

KL
KL on 13 Nov 2017
Edited: KL on 13 Nov 2017
In MATLAB indexing is inherent, be it array or tables. If you have a table like,
dummy = {'call',366;'free',216;'txt',163};
t = cell2table(dummy,'v',{'words','count'})
t =
words count
______ _____
'call' 366
'free' 216
'txt' 163
there are number of ways you can access the content of it. This is well explained in the documentation,
To simplify,
--> to access a column, you can either use.
>> t.words
ans =
'call'
'free'
'txt'
or
>> t{:,1}
ans =
'call'
'free'
'txt'
--> just to access specific row of that column,
>> t.words(1)
ans =
'call'
or
>> t{1,1}
ans =
'call'
As you can see, creating a new column called index is completely redundant.

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!