for loop and indexing a matrix help

조회 수: 2 (최근 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 CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by