for loop and indexing a matrix help

14 views (last 30 days)
Aroi Mehu
Aroi Mehu on 23 Apr 2020
Commented: Aroi Mehu on 23 Apr 2020
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?

Answers (1)

KSSV
KSSV on 23 Apr 2020
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 Comment
Aroi Mehu
Aroi Mehu on 23 Apr 2020
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).

Sign in to comment.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!