replacing ascending numbers with continous numbers

Hello everybody,
I am looking for a fast and efficient way to convert a vector of non continous ascending numbers to continous numbers.
As an example:
The vector
[4 20 35 22 10 49]
should become
[1 3 5 4 2 6]
at the moment I'm using a for loop, look for the lowest number write the runtime index into the result vector and set the position in the original vector to an illegal value. I know this is not the best way but it was the only one I could think of.
Also I'm not doing a single vector at a time but doing this to the columns of a matrix.
Thank you

 採用された回答

Amit
Amit 2014 年 1 月 22 日

1 投票

A = [4 20 35 22 10 49];
B = 1:numel(A);
[~,C] = sort(A);
B(C) = B; % Your vector

3 件のコメント

Daniel
Daniel 2014 年 1 月 22 日
Thank you! Do you happen to know a way to extend this to a matrix? I.e. do this to every column of a matrix at once.
Amit
Amit 2014 年 1 月 22 日
% Your matrix is named A
[m,n] = size(A);
B = 1:m;
[~,C] = sort(A);
D = zeros(m,n);
for i = 1:n
D(C(:,i),i) = B;
end
Daniel
Daniel 2014 年 1 月 22 日
Mile grazie! Thank you very much. This is way more elegant than anything I managed to butchered.

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeData Type Conversion についてさらに検索

製品

質問済み:

2014 年 1 月 22 日

コメント済み:

2014 年 1 月 22 日

Community Treasure Hunt

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

Start Hunting!

Translated by