for loop and indexing a matrix help

12 ビュー (過去 30 日間)
Aroi Mehu
Aroi Mehu 2020 年 4 月 23 日
コメント済み: Aroi Mehu 2020 年 4 月 23 日
Trying to make a function that if i input a matrix(x) and its conditions(cond), (x,cond)- it will resutun the index(row numders) that meet the conditions, as a vector. Any good examples of how this can be executed. Or if matlab has any helpful docs that can help?

回答 (1 件)

KSSV
KSSV 2020 年 4 月 23 日
A = rand(5) ;
idx = A>0.7 ; % indices greater than 0.7
find(idx)
A(idx)
idx = A<0.5 ; % indices less than 0.5
find(idx)
A(idx)
idx = A>0.3 & A<0.7 ; % indices greater than 0.3 and less than 0.7
find(idx)
A(idx)
  1 件のコメント
Aroi Mehu
Aroi Mehu 2020 年 4 月 23 日
that makes sense but how about using for loops? For example the function below
Inputs for example :
x = [1 2 3 4; 70 62 45 65; 23 17 19 20; 51 34 56 72];
conditions = [60 20 50];
ind = avada(x,cond)
function ind = avada(x,cond)
y = false(size(x)-[1 0]); %iNITIALIZE Y
for i=1:size(x,2)-1 % Run for loop for 3 times i.e. 1 less than 4
y(i,:) = x(i+1,:)>=cond(i);% condition,all values greater than equal to cond will be true
end
ind = x(1,sum(y)== (size(x,2)-1)); %
end
those inputs give me a correct result, however,
when i try to input x =[1 2 3 4 5 6 7 8 9 10; 70 70 62 45 65 88 69 10 56 92; 23 17 19 20 19 17 20 21 23 24; 51 34 56 72 77 88 99 49 50 70] with the same conditions, it says
Index in position 1 exceeds array bounds (must not exceed 4).

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

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by