任意の値が配列の中にあるか検索したい
46 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Y.T
le 16 Déc 2022
Réponse apportée : Hernia Baby
le 16 Déc 2022
以下の2つの配列z1,z2があるとします。
z1=[18.0 17.3 16.6 ; 16.1 15.3 15.4];
z2=[14.3 15.7 16.0 ; 16.9 17.5 15.8];
この中から任意の値(仮に15.2とします)が存在するかを検索し、
①存在する場合には、どの配列の何行何列かを出力結果として出力、
②存在しない場合には、任意の値から最も近い値(誤差範囲 ±0.2)を出力し、その値はどの配列の何行何列かを出力結果として出力
する方法はありますでしょうか。
(②の例)
任意の値 15.2 が存在していないため、任意の値から最も近い値 15.4 (誤差範囲 ±0.2)を出力し、その値は z2 の2行3列に存在していることを出力結果として出力したい。
Réponse acceptée
Hernia Baby
le 16 Déc 2022
関数にしました
z1=[18.0 17.3 16.6 ; 16.1 15.3 15.4];
z2=[14.3 15.7 16.0 ; 16.9 17.5 15.8];
num = 15.2;
th = 0.2;
I1 = MySearch(z1,num,th)
I2 = MySearch(z2,num,th)
関数について
function I = MySearch(x,num,th)
idx1 = abs(x - num) <= th; % 誤差範囲内に数字があるか判別
[~,idx2] = min(abs(x - num),[],'all'); % 差が最小となる点を探す
idx3 = x(idx2) == x; % indexの形にする
idx = idx1 & idx3; % 誤差範囲内かつ最小が最近傍
[r,c] = find(idx); % 行と列をさがす
I = [r,c]; % 1つにまとめる
end
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!