Hi,
I have d = {[5:10] [20:30]}; e = [1 2 7 8 9 11 12 15 16 22 25 30 35 40 45]; I want to extract values from e which falls into vectors of d.
Result = { [7 8 9] [22 25 30] } because 7, 8 and 9 are within 5 and 10; 22, 25 and 30 are within 20 and 30.
The code I tried gave what I want but when i == 3, the error happened. How can I stop j loop when all vectors in d have been checked. Thank you!
clc; clear; close all
d = {[5:10] [20:30]};
e = [1 2 7 8 9 11 12 15 16 22 25 30 35 40 45];
E = length(e);
D = length(d);
for i = 1:D
while j <= max(d{end})
for j = 1:E
if e(j) >= min(d{i})
a(i) = e(j);
for k = j+1:E
if e(k) > max(d{i})
b(i) = e(k-1);
want{i} = [e(j:k-1)];
if ~isempty(b(i))
j=k;
i=i+1;
break;
end
end
end
end
end
end
end

 採用された回答

KSSV
KSSV 2020 年 5 月 23 日

0 投票

Why you have made code that complex? It is a simple task. You can use intersect.
d = {[5:10] [20:30]};
e = [1 2 7 8 9 11 12 15 16 22 25 30 35 40 45];
N = length(d) ;
result = cell(N,1) ;
for i = 1:N
iwant{i} = intersect(e,d{i}) ;
end

6 件のコメント

HYZ
HYZ 2020 年 5 月 23 日
thank you!
HYZ
HYZ 2020 年 5 月 23 日
編集済み: HYZ 2020 年 5 月 23 日
Sorry ... I didn't think far. my real data are something like
d = {[5:10] [20:30]}; e = [1 2 7.5 8.5 9.5 11 12 15 16 22.5 25.5 30 35 40 45];
the elements in e might not be exactly same as in d. they are juz within the range of each vector in d.
Could you advise? thanks.
KSSV
KSSV 2020 年 5 月 23 日
What is expected output here?
HYZ
HYZ 2020 年 5 月 23 日
Output will be { [7.5 8.5 9.5] [22.5 25.5 30]}. thanks
KSSV
KSSV 2020 年 5 月 23 日
Have a look on knnsearch, ismembertol.
HYZ
HYZ 2020 年 5 月 23 日
I used 'find' to do it. Anyway thanks. I learnt "intercept"
clc; clear; close all
d = {[5:10] [20:30]};
e = [1 2 7.5 8.5 9.5 11 12 15 16 22.5 25.5 30 35 40 45];
D = length(d);
iwant = cell (1,D);
for i = 1:D
loc {i} = find(e >= min(d{i}) & e <= max(d{i}));
iwant{i} = [e(loc{i})];
end

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

質問済み:

HYZ
2020 年 5 月 23 日

コメント済み:

HYZ
2020 年 5 月 23 日

Community Treasure Hunt

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

Start Hunting!

Translated by