I have an array of numbers ranging from 95 to 116. I would like to have the numbers closest to 99 in value be 99, the numbers closest to 104 in value be 104 and the number closest to 115 in value be 115. How could code this? Thanks for the help.

 Akzeptierte Antwort

Roger Stafford
Roger Stafford am 28 Apr. 2016

1 Stimme

Let the "numbers ranging from 95 to 116" be in a row vector u, and the numbers 99, 104, and 115 be in a column vector v.
[~,ix] = min(abs(bsxfun(@minus,u,v)),[],1);
u = v(ix);
Then u will now be as required.

3 Kommentare

shellmcg
shellmcg am 28 Apr. 2016
Wow, Thanks Roger. Do you mind explaining what your code did please? Thanks Heaps
The bsxfun(@minus,u,v) part finds the difference between each value in v and each value in u. The result will be a rectangular matrix of differences, between u and v values with the different u values along the horizontal direction and v values changing along the vertical direction. The 'abs' operation converts these differencess to their absolute values. The min(...,[],1) step finds the minimum of these absolute in each column and thereby finds the closest v value to the u value for that column. The ix indexes these. The final operation v(ix) is just choosing for each u value the corresponding ix value which references that closest v value.
I suggest you break the operations up like this:
t1 = bsxfun(@minus,u,v);
t2 = abs(t2);
[~,ix] = min(t2,[],1);
and study t1, t2, and ix. You will see how they lead to the desired result.
Make sure u is a row vector, that is, it has only one row, and v is a column vector, meaning it has only one column.
One could also make use of 'histc'. Using the same u and v I previously defined, do this:
w = sort(v);
x = [-inf;(w(1:end-1)+w(2:end))/2;inf];
[~,ix] = histc(u,x);
u = w(ix);
This would be more efficient if v were very long.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Steven Lord
Steven Lord am 28 Apr. 2016

1 Stimme

Use interp1 with the 'nearest' method.

Kategorien

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by