Sorting numbers according to elements of an array

조회 수: 4 (최근 30일)
Hans123
Hans123 2020년 5월 29일
편집: per isakson 2020년 5월 29일
Sorry for the vague title, I asked a similar question earlier very poorly and I extracted the most fundamental concept that I am trying to wrap my head around and I hope I will be articulate enough this time.
I want to sort elements accordingly;
I have 3 elements in my SORTING array, 3, 7 and 11
My input is 4.1, since this is closest to 3, the output will be equal to 3. Looking at it, it seems intuitive but I am struggling on how to break this down to explain it to MATLAB
In reality I am working with numbers sensitive to the 4th decimal place, but I am trying to understand the concept behind this sorting method
SORTING = [3 7 11]';
input = 4.1;
%code to compute which number it is closest to
output = 3;
%further calulcations based on output

채택된 답변

KSSV
KSSV 2020년 5월 29일
편집: KSSV 2020년 5월 29일
SORTING = [3 7 11]';
input = 4.1;
%code to compute which number it is closest to
% output = 3;
% GEt the absolute difference with given input and it's minimum
[val,idx] = min(abs(SORTING-input)) ;
output = SORTING(idx)

추가 답변 (1개)

per isakson
per isakson 2020년 5월 29일
편집: per isakson 2020년 5월 29일
Without comment:
>> [~,ix]=min(abs(SORTING-input))
ix =
1
>> SORTING(ix)
ans =
3
>>
>> [~,ix]=min(abs(SORTING-12))
ix =
3
>> SORTING(ix)
ans =
11

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by