![](/img/trans.png)
[英]Use of Matlab find function for getting index of a vertex using its coordinates
[英]How to use index in MATLAB to find function constraints
我想返回滿足某些條件的元素索引以及它們的索引應該在某些常量A
和B
之間的條件。 有一種天真的形式實現這一點:
inds=find(conditions)
real_inds=find(A<=inds<=B)
但它效率低下,實際上我想將搜索限制在這些常量之間具有索引的元素,而不是所有元素。
如何將自己限制在A
, B
范圍內?
假設您有my_vector
並且希望找到大於0.3且小於0.5的元素(“ conditions
”)。 將自己限制在A
, B
范圍內只需:
masked_ind = find(my_vector(A:B) > 0.3 & my_vector(A:B) < 0.5);
real_ids = masked_ind + A - 1; %// correct the offset induced by `A`.
通過在my_vector(A:B)
上應用conditions
,您實際上並不關心my_vector
有多大,而且您只處理A:B
范圍內A:B
元素。
順便說一句,您是否考慮過使用Andras Deak建議的邏輯索引 ,而不是使用find
和實際的線性索引?
%// create a mask to keep indices from A to B only
real_inds_logical = false(size(your_vector));
real_inds_logical(A:B) = (my_vector(A:B)>0.3 & my_vector(A:B)<0.5);
你可以這樣做:
假設你有向量x
,條件: x == 7 or ( x > 3 and x < 5)
你想要在A和B之間搜索。
現在將向量g
定義為索引的輔助向量:
g = 1:length(x);
然后得到這樣的指數:
indices = g( (g >= A) & (g <= B) & (conditions) );
在這種情況下,這被翻譯為:
indices = g( (g >= A) & (g <= B) & (x == 7 | (x > 3 & x < 5)) );
這將返回滿足extern括號之間條件的g
元素。
示例代碼 :
初始值:
x = [0.0975 0.2785 0.5469 0.9575 0.9649 0.1576 0.9706 0.9572 0.4854 0.8003];
A = 4;
B = 9;
條件: x >= 0.1
且x <= 0.7
碼:
g = 1:length(x);
indices = g((g >= A) & (g <= B) & (x <= 0.7) & (x >= 0.1));
結果:
indices =
6 9
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.