How can I grab the value of i for which out(i) is equal to s(2)?

조회 수: 1 (최근 30일)
Preyanka Dey
Preyanka Dey 2020년 9월 4일
댓글: Star Strider 2020년 9월 4일
Hi everyone,
I am trying to grab the value of i for which out(i) is equal to s(2). The segment is marked below by '% facing problem here'. Correct value of d is the answer. Can anyone please help me to figure that out? thanks a lot.
function main
n = 6;
long_min = 1.;
lat_min = 1.;
w = 2.;
h = 1.;
bound.xmin = long_min;
bound.xmax = long_min + w;
bound.ymin = lat_min;
bound.ymax = lat_min + h;
% generating the sample points
long = long_min + w * rand(1,n);
lat = lat_min + h * rand(1,n);
%structure arrays
pts = struct('num',{},'x',{},'y',{});
for i=1:n
pts(i).num=i;
pts(i).x=long(i);
pts(i).y=lat(i);
end
a = 5;
for i = 1:n
out(i) = near_pt(pts(i).x, pts(i).y, pts(a).x, pts(a).y)
end
% facing problem here
s = sort(out(:));
if (out(i)== s(2))
d = [i]; % return the value of i for which out(i)== s(2)
end;
disp(d);
end
function out = near_pt(p, q, r, s)
out = sqrt((r - p)^2+(s - q)^2);
end

채택된 답변

Star Strider
Star Strider 2020년 9월 4일
편집: Star Strider 2020년 9월 4일
What you want to do is not obvious.
If you want to know the index of the second value of ‘s’ (the second lowest value of ‘out’ with ‘out’ sorted ascending), that is striaghtforward:
[s,idx] = sort(out(:))
since ‘s’ will be the sorted values of ’out’ and ‘idx’ will be their original locations in the ‘out’ vector.
In one run of your code:
s =
0.0000e+000
1.2888e+000
1.5399e+000
1.6480e+000
1.8415e+000
1.8834e+000
idx =
5
4
2
6
1
3
so the second value of ‘s’ was originally ‘out(4)’.
EDIT —
d = idx(2)
Is that the result you want?
  댓글 수: 2
Preyanka Dey
Preyanka Dey 2020년 9월 4일
편집: Preyanka Dey 2020년 9월 4일
@Star Strider Thanks a lot for the solution. Yes I want idx(2).
Star Strider
Star Strider 2020년 9월 4일
As always, my pleasure!

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

추가 답변 (1개)

David Hill
David Hill 2020년 9월 4일
function main
n = 6;
long_min = 1.;
lat_min = 1.;
w = 2.;
h = 1.;
bound.xmin = long_min;
bound.xmax = long_min + w;
bound.ymin = lat_min;
bound.ymax = lat_min + h;
% generating the sample points
long = long_min + w * rand(1,n);
lat = lat_min + h * rand(1,n);
%structure arrays
pts = struct('num',{},'x',{},'y',{});
for i=1:n
pts(i).num=i;
pts(i).x=long(i);
pts(i).y=lat(i);
end
a = 5;
for i = 1:n
out(i) = near_pt(pts(i).x, pts(i).y, pts(a).x, pts(a).y);
end
% facing problem here
s = sort(out(:));
d=find(out==s(2));
disp(d);
end
function out = near_pt(p, q, r, s)
out = sqrt((r - p)^2+(s - q)^2);
end

카테고리

Help CenterFile Exchange에서 Pie Charts에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by