How to replace duplicate elements with the elements of the second array?
5 ビュー (過去 30 日間)
表示 古いコメント
Hi , I have two arrays , one with duplicate elements and I want to keep the first occurance of the element and replace other repeated values with the elements of the second array. Here is the example
a=[23 34 56 78 100 10 12];
b= [2 2 2 4 6 0 0 11 11 11 6];% contains repeating elements
iwant=[2 23 34 4 6 0 56 78 11 100 10 12]
採用された回答
Voss
2023 年 1 月 31 日
Maybe something like this?
a = [23 34 56 78 100 10 12];
b = [2 2 2 4 6 0 0 11 11 11 6];% contains repeating elements
yougot = b;
a_idx = 1;
for ii = 1:numel(b)
if any(b(1:ii-1) == b(ii))
yougot(ii) = a(a_idx);
a_idx = a_idx+1;
end
end
if a_idx <= numel(a)
yougot = [yougot a(a_idx:end)];
end
disp(yougot);
iwant = [2 23 34 4 6 0 56 78 11 100 10 12];
disp(iwant);
Note that the 11 and the 78 are switched in iwant vs yougot. I think that's a mistake in iwant, according to the description of the algorithm you gave.
その他の回答 (1 件)
Fabio Curto
2023 年 1 月 31 日
Hi,
If i get the question correctly, you want to append the remaining unused elements of a. I wrote a basic idea, maybe it can be optimized in some way!
a=[23 34 56 78 100 10 12];
b= [2 2 2 4 6 0 0 11 11 11 6];% contains repeating elements
changed = 1; % flag initialization
j = 1; % a vector index
for i=2:length(b)
if changed == 1
temp = b(i-1);
end
if b(i) == temp
b(i) = a(j);
j = j+1;
changed = 0;
else
changed = 1;
end
end
for j=j:length(a)
b = [b a(j)];
end
Hope it is helpful,
参考
カテゴリ
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!