Round towards specific values in an array

58 ビュー (過去 30 日間)
Rob
Rob 2011 年 3 月 29 日
回答済み: Steven Lord 2022 年 8 月 8 日
Hi, when I have 2 vectors, one vector has a larger length than the other. But they both have values that are approximately the same. Now I want to round and locate each element of the large vector in the short vector. So, for example:
A = [2000 1999 1998 1996 1993 .... 0] (dim=1 x a)
B = [2000 1995 1990 1985 1980 .... 0] (dim=1 x b)
I would now like to see that for example {2000 1999 1998} of A are rounded to {2000} in B and {1996 1993} in A to {1995} in B so that I can find the index of an element in B that corresponds to one (or more) rounded values in A.
I can imagine that you can do this with some kind of for-loop, but preferably I do not use that since it will become a nested loop and will cost a lot of computation time.
THanks a lot

回答 (4 件)

Tom Gaudette
Tom Gaudette 2011 年 3 月 29 日
% This solutions currently does it with loops just to get a picture of the problem.
A = [2000 1999 1998 1996 1993 1990];
B = [2000 1995 1990 1985 1980];
for idx1=1:length(A);
for idx2=1:length(B);
C(idx2,idx1)=A(idx1)-B(idx2);
end;
end
% Now find the index of the min values
[v,i]=min(abs(C));
% 'i' now contants the list of locations in B that corespond to the nearest
% A value
B(i)
  1 件のコメント
Adnane Youcef
Adnane Youcef 2022 年 8 月 8 日
編集済み: Adnane Youcef 2022 年 8 月 8 日
it works thnx

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


Teja Muppirala
Teja Muppirala 2011 年 3 月 29 日
This is one possible solution. If your vectors are very long though, this might be inefficient because it temporarily makes a big matrix to calculate all the differences.
A = -5 + 35*rand(1,100);
B = 0:5:25;
[~,I] = min(abs(bsxfun(@minus,A,B')));
Anew = B(I);
[A; Anew]

Tom R
Tom R 2012 年 7 月 31 日

Steven Lord
Steven Lord 2022 年 8 月 8 日
A = [2000 1999 1998 1996 1993].';
B = [2000 1995 1990 1985 1980].';
Assuming all the elements of B are unique, interpolate to 'nearest'.
C = interp1(B, B, A, 'nearest');
result = table(A, C, 'VariableNames', ["Original data", "Rounded data"])
result = 5×2 table
Original data Rounded data _____________ ____________ 2000 2000 1999 2000 1998 2000 1996 1995 1993 1995

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by