Consider the two vectors:
v= [1 2 3 4 5 6 7]
a=['a' 'b' 'c' 'a' 'a' 'a' 'd']
I want to find the mean of all entries in v whose corresponding entries in a is ‘a’;
i.e. test= mean(1,3,4,5)
I have tried this for a start to catch the entries:
for i=1:7
if abs(char(a(i))-char(c))==0;
test(i)=v(i);
end
end
test
test = 1 0 0 4 5 6
PROBLEMS:
- It is assigning 0 for entries not found
- It is not considering last term
Try using the
ismemberfunction:ismemberforms yourtestvector as a logical array, assigning 1 where the character ‘a’ is found in your vector, and 0 where it isn’t:You can then use this as a logical index to extract the corresponding entries from your vector
v:Finally, you can take the mean of this vector:
EDIT
I have realised that in your case, you can actually form your logical array in a much simpler way, using a comparison operator:
So your final line of code will look like so:
ismemberis useful where you want to test for the presence of more than one character, for example if you wanted to find locations where ‘a’ or ‘b’ were.