selecting an element of a vector

조회 수: 12 (최근 30일)
PJS KUMAR
PJS KUMAR 2018년 10월 23일
답변: PJS KUMAR 2018년 10월 25일
How to select an element of a vector which is nearest to the given value xp.
Suppose we have a vector
x=[1 1.05 1.1 1.15 1.2 1.25]
a) if xp=1.18, the output should be 1.2 (which is nearest to 1.18)
b) if xp=1.12, the output should be 1.1 (which is nearest to 1.12)
  댓글 수: 2
madhan ravi
madhan ravi 2018년 10월 23일
편집: madhan ravi 2018년 10월 23일
b) if xp=1.12, the output should be 1.1 (which is nearest to 1.12)
nearest to 1.12 is 1.15 ?? not 1.1 , whats the logic behind it ,explain to understand
PJS KUMAR
PJS KUMAR 2018년 10월 23일
1.1 is nearest to 1.12 than 1.15

댓글을 달려면 로그인하십시오.

채택된 답변

KALYAN ACHARJYA
KALYAN ACHARJYA 2018년 10월 23일
편집: KALYAN ACHARJYA 2018년 10월 23일
x=[1 1.05 1.1 1.15 1.2 1.25];
xp=input('Enter the xp value: ');
[d, idx]=min(abs(x-xp));
fprintf('The output is%.2f',x(idx));
Command Window
Enter the xp value: 1.18
The output is1.20
  댓글 수: 2
PJS KUMAR
PJS KUMAR 2018년 10월 23일
What is [d, idx]
KALYAN ACHARJYA
KALYAN ACHARJYA 2018년 10월 23일
편집: KALYAN ACHARJYA 2018년 10월 23일
idx is giving the index position of x, which is close to xp
if idx=1, that means x(idx)=x(1)=1 (First element)
d gives the minimum difference of x-xp, abs absolute value (+ve)

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

PJS KUMAR
PJS KUMAR 2018년 10월 25일
How to select an element of a vector which is previous to the given value xp.
Suppose we have a vector
x=[1 1.05 1.1 1.15 1.2 1.25]
a) if xp=1.18, the output should be 1.15 (which is previous to 1.18)
b) if xp=1.12, the output should be 1.1 (which is previous to 1.12)

카테고리

Help CenterFile Exchange에서 Map Display에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by