find & replace data in array

3 ビュー (過去 30 日間)
Pierre
Pierre 2013 年 9 月 17 日
Hi, I have two arrays.
A=[7 14 21 28 35 42 49 56 63 70 77 84 91]
B=[22 55]
I wanna find the number in A which is close to the number in B and to replace the number in A by the number in B. Finally, A will be
A=[7 14 22 28 35 42 49 55 63 70 77 84 91].
Is there any better and faster algorithm to solve this issue? Thanks

採用された回答

Roger Stafford
Roger Stafford 2013 年 9 月 17 日
[~,p] = min(abs(bsxfun(@minus,A,B')),[],2);
A(p) = B;
There is an inherent ambiguity possible in this problem. An element in A that happens to be the closest one to both of two different elements of B could legitimately be replaced by either B element. In the above algorithm it is always the later one in B that does the replacing in such cases.

その他の回答 (2 件)

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 9 月 17 日
A=[7 14 21 28 35 42 49 56 63 70 77 84 91]
B=[22 55]
for k=1:numel(B)
[ii,ii]=min(abs(A-B(k)));
A(ii)=B(k);
end

Andrei Bobrov
Andrei Bobrov 2013 年 9 月 17 日
編集済み: Andrei Bobrov 2013 年 9 月 17 日
A=[7 14 21 28 23 35 21 42 49 56 63 70 54 77 84 91]
B = [22 55]
M = abs(bsxfun(@minus,A,B'));
t = bsxfun(@eq,M,min(M,[],2));
add1 = bsxfun(@times,t,B');
A(any(t)) = add1(t)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by