# adding index to matrix rows

70 views (last 30 days)
Ali on 27 May 2016
Commented: Ali on 27 May 2016
I have a matrix like this
1 0
0 2
2 1
0 3
3 2
2 0
4 1
1 6
6 4
6 1
0: 1 0
1: 0 2
2: 2 1
3: 0 3
4: 3 2
5: 2 0
6: 4 1
7: 1 6
8: 6 4
9: 6 1

Guillaume on 27 May 2016
Edited: Stephen Cobeldick on 27 May 2016
Please use the code format button {}Code rather than putting spaces between each line.
A matrix can only contain numbers, colons are not allowed. If it's only for display that you want that, there's no simple way to force matlab to display matrices like this.
Possibly, you can convert the matrix into a table and assign names to the rows:
m = [1 0;0 2; 2 1; 0 3; 3 2; 2 0; 4 1];
t = array2table(m, 'RowNames', sprintfc('%d:', 1:size(m, 1)), 'VariableNames', sprintfc('col%d', 1:size(m, 2)))
Otherwise, you'll have to write your own display function which is far from trivial if you want it to play nicely with format.

Ali on 27 May 2016
I used Guillaume code, but I still have a problem here. I would like to first line start with zero and not one. the code gives me this:
1: 1 0
2: 0 2
3: 2 1
4: 0 3
5: 3 2
but I want this:
0: 1 0
1: 0 2
2: 2 1
3: 0 3
4: 3 2
Guillaume on 27 May 2016
Well simply modify the relevant fprintf:
fprintf('%d:', row - 1);
Ali on 27 May 2016
Many thanks Guillaume. you helped me a lot

Renato Agurto on 27 May 2016
Edited: Renato Agurto on 27 May 2016
Is this what you want? Or what do you mean with ':' in a matrix?
A = [1 0;
0 2;
2 1;
0 3;
3 2;
2 0;
4 1;
1 6;
6 4;
6 1];
B = [(0:size(A,1)-1)' A];

#### 1 Comment

Ali on 27 May 2016
Many thanks for the response. It is appreciated. I have a matrix with 500 row and 2 columns. I would like to be converted in this format: for instance, this is part of the results that I am looking for
0: 1 0
1: 0 2
2: 2 1
3: 0 3
4: 3 2
5: 2 0
6: 4 1