How to replace repeating no.s in an array by distinct no.?

1 回表示 (過去 30 日間)
Abdul Gaffar
Abdul Gaffar 2017 年 11 月 3 日
編集済み: Guillaume 2017 年 11 月 3 日
Let n=10 Consider array A={7,6,3,5,3,6,6,2,9,6} Algorithm: replace the repeating no. by its maximum unused value & I want all no.s between 1 & 10. How can it be done??
  1 件のコメント
Guillaume
Guillaume 2017 年 11 月 3 日
I'm assuming that
A = [7,6,3,5,3,6,6,2,9,6]
i.e. it is a regular matrix, not a cell array as you've written.
What do you want as an output?

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

採用された回答

Andrei Bobrov
Andrei Bobrov 2017 年 11 月 3 日
A=[7,6,3,5,3,6,6,2,9,6]
[a,b] = unique(A,'first');
out = zeros(10,1);
out(b) = a;
out(out==0) = setdiff(1:10,a)

その他の回答 (2 件)

KSSV
KSSV 2017 年 11 月 3 日
編集済み: KSSV 2017 年 11 月 3 日
A = randperm(10) ;

Guillaume
Guillaume 2017 年 11 月 3 日
編集済み: Guillaume 2017 年 11 月 3 日
If I understood correctly:
A = [7,6,3,5,3,6,6,2,9,6]
[~, ~, subs] = unique(A);
idxtoreplace = accumarray(subs, (1:numel(A))', [], @(idx) {idx(2:end)});
idxtoreplace = vertcat(idxtoreplace{:});
replacementvals = setdiff(1:numel(A), A);
A(idxtoreplace) = replacementvals(1:numel(idxtoreplace));
Note that which of the duplicate gets replaced and by which value may change with matlab versions, but you're guaranteed that all but 1 of the duplicated values is replaced by an unused value.

カテゴリ

Help Center および File ExchangeElementary Math についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by