フィルターのクリア

Combining two vectors into a new one

12 ビュー (過去 30 日間)
Irem Sara
Irem Sara 2022 年 3 月 11 日
コメント済み: Irem Sara 2022 年 3 月 11 日
Hi,
I am working on a dynamic programming problem and I now have two equal-sized vectors, say vector A and B. I am trying to generate a new vector that starts with the first element of vector B, then finds the closest value in A and takes it's index value, then records the value corresponding to this index in B. I want to make a loop and cover all values in my vector B. Is there a way to code this? (Vector A and B won't have the exact same values unfortunately, so the code will need to find the closest element's index)
Thanks!

採用された回答

Johan
Johan 2022 年 3 月 11 日
I don't know if there is a builtin function to do that but you can achieve using translation, logical condition and find:
A = randi(10,5,1);
B = randi(10,5,1);
% compute difference of each element of B with each element of A
abs(B'-A)
ans = 5×5
1 0 3 4 3 2 1 2 3 2 4 3 0 1 0 5 4 1 0 1 4 3 0 1 0
% minimum difference value
min(abs(B'-A))
ans = 1×5
1 0 0 0 0
% Create a logical mask of the position of the minimum difference
min_distance_mask = abs(B'-A) == min(abs(B'-A))
min_distance_mask = 5×5 logical array
1 1 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 1 0 0 0 1 0 1
%use find to get the index and rescale the index using the width of the array
%Equal distance increase the size of C compared to A and B
C = mod(find(min_distance_mask)-1,size(min_distance_mask,2))+1
C = 7×1
1 1 3 5 4 3 5
  1 件のコメント
Irem Sara
Irem Sara 2022 年 3 月 11 日
This is exactly what I was looking for- thank you so much!

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

その他の回答 (1 件)

KSSV
KSSV 2022 年 3 月 11 日
A = rand(3) ;
B = rand(2) ;
idx = knnsearch(B(:),A(:))
Also have a look on ismember, ismembertol.

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by