I have a matrix column with a number in each row, but they are not consecutive (per example, from 3 it jumps to 6). How can I turn them into a consecutive order?

3 ビュー (過去 30 日間)
I have a matrix column with a number in each row, but they are not consecutive (per example, from 3 it jumps to 6). How can I turn them into a consecutive order?
  9 件のコメント
Walter Roberson
Walter Roberson 2017 年 1 月 9 日
I really do not understand the rule to be followed! Why are only the 10 and 12 changed? Why should they become 6 and 9?? How does this generalize?
Eduardo Rocha
Eduardo Rocha 2017 年 1 月 9 日
Sorry, I gave a bad example. This one is what really happens:
A = [0,1,2,3,6,3,10,6,6,10,12,12,0,2];
It should turn into:
B = [0,1,2,3,4,3,5,4,4,5,6,6,0,2];

サインインしてコメントする。

採用された回答

Walter Roberson
Walter Roberson 2017 年 1 月 9 日
A = [0,1,2,3,6,3,10,6,6,10,12,12,0,2];
[~, ~, idx] = unique(A);
t = 0:max(idx)-1;
B = t(idx);
Note: this code relies upon the expected lowest value being 0.

その他の回答 (1 件)

Niels
Niels 2017 年 1 月 9 日
編集済み: Niels 2017 年 1 月 9 日
depending on what you really mean by "sorting" and "consecutive", here are 2 different solutions:
A=randi(10,12,4)
A =
8 2 2 2
9 9 2 8
9 6 3 4
1 6 5 3
4 2 1 5
3 9 10 1
9 7 10 2
5 4 5 10
10 6 5 10
2 5 4 6
3 1 10 1
2 3 4 3
% use sort if you just want to sort them
>> A(:,3)=sort(A(:,3))
A =
8 2 1 2
9 9 2 8
9 6 2 4
1 6 3 3
4 2 4 5
3 9 4 1
9 7 5 2
5 4 5 10
10 6 5 10
2 5 10 6
3 1 10 1
2 3 10 3
% but if u want to make them consecutive => (1:#rows)
>> A(:,3)=1:12
A =
8 2 1 2
9 9 2 8
9 6 3 4
1 6 4 3
4 2 5 5
3 9 6 1
9 7 7 2
5 4 8 10
10 6 9 10
2 5 10 6
3 1 11 1
2 3 12 3

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by