Check if a certain value is in the vector

Asked

Viewed 46 times

1

I created the vector fragil that will accept various inputs from the user, inputs that will (or will not) be the position of other elements in another matrix. I used the following function to create the vector fragil:

fragil = zeros(1, numIdosos);

And then I wanted to check on the second if of the excerpt below if the j belongs to the vector fragil. I mean, is there any way to verify that the j belongs to the vector fragil without adding the for extra that travels the vector fragil whole?

for j=1:numIdosos
     if MCobertura(iMax,j)==1
             contador(j)=contador(j)+1;
     end
     if contador (j)>1 
         porCobrir(j)=0;
     end
 end
 n_porCobrir=sum(porCobrir);
end
end

1 answer

1

You can use the find to return the index if the number you are looking for exists inside the vector:

x = [1     3     5     7     9    11    13    15    17    19]

k = find(x==3);

if isempty(k)

    disp('nao achei')

else

    disp('achei')

end

In the above example I am using the find to find the occurrence of the number 3 within the vector x, if found it will place the index inside the variable k, after that I compare with the if if there was a return or not, if the variable k empty there is no occurrence of the number you are looking for in the vector.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.