Find position of the values of an array in a second array

2 ビュー (過去 30 日間)
raktim banerjee
raktim banerjee 2011 年 1 月 25 日
There is 2 strings 'dls' & 'look'. I want to find exact lower and exact higher value of every elements of 'dls' in the sorted string 'look'. I wrote this:
dls = [5 2 1 7 4];
look = [-0.6 1 2.6 4.2 5.8 7.4];
s = length(dls);
l = length(look);
dlstr = 0;
dhstr = 0;
for i = 1:s,
for j =1:l,
if dls(i)>=look(j)
continue; %j=j+1;
else
dh = look(j);
dl = look(j-1);
dlstr = [dlstr dl];
dhstr = [dhstr dh];
break;
end
end
end
dhstr(1)=[];
dlstr(1) = [];
dlstr
dhstr
The expected result is:
dlstr =
4.2000 1.0000 -0.6000 5.8000 2.6000
>> dhstr
dhstr =
5.8000 2.6000 1.0000 7.4000 4.2000
but the output is:
dlstr =
4.2000 1.0000 1.0000 5.8000 2.6000
dhstr =
5.8000 2.6000 2.6000 7.4000 4.2000
The problem occurred if any value in both strings match. '1' exists in both string. dlstr(3) should be -0.6000 & dhstr(3) should be 1.000. Please tell me how to overcome this problem?
  2 件のコメント
Paulo Silva
Paulo Silva 2011 年 1 月 25 日
"There is 2 strings 'dls' & 'look'"
I disagree, they look like arrays not strings
raktim banerjee
raktim banerjee 2011 年 1 月 25 日
Sorry sir! Yes, those are array.

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

採用された回答

Ashish Uthama
Ashish Uthama 2011 年 1 月 25 日
With the above code, this correction should yield you your required output:
dls(i)>look(j)
You might be able to write this functionality more compactly by using the function find. Also: If you find the lower bound first, and the 'look' array is expected to be sorted, then wont the higher bound be the next element?
  1 件のコメント
raktim banerjee
raktim banerjee 2011 年 1 月 25 日
Thanks a lot. It works.

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

その他の回答 (1 件)

Todd Flanagan
Todd Flanagan 2011 年 1 月 25 日
This:
dls(i)>=look(j)
Should be:
dls(i)>look(j)
You might be able to write this functionality more compactly by using the function find.
Note that because the array is sorted, you can find 1 bound and infer both.
  3 件のコメント
raktim banerjee
raktim banerjee 2011 年 1 月 25 日
Thanks a lot. It works.
Ashish Uthama
Ashish Uthama 2011 年 1 月 25 日
yup, its better this way.

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

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by