How do I count vectors with a specified value in an array of equal length vectors in Matlab?

4 views (last 30 days)
I am trying to implement a counting function that takes a value along with an array of vectors and returns the number of VECTORS that contain the given value. For example, two of the vectors in the array may look like this:
{vhigh,vhigh,2,2,small,low,unacc}
{vhigh,low,2,2,small,low,unacc}
As you can see some of the values are repeated twice within the same vector, however I only want to count the ENTIRE vector that contains the given value as ONE unit. So if I give my function the value vhigh, I would like it to only count each of the above vectors ONE time.
Right now this is what I have:
function result = countValue(value, dataArray )
count = 0;
for i=1:size(dataArray) - 1,
if (dataArray(i) == value)
count = count + 1;
end
end
result = count;
end
The problem with my function right now seems to be that it will count the value individually. It would return 3 if given vhigh right now for the above example, when I only want it to return 2 because 2 vectors within the array contain vhigh.
  1 Comment
Geoff Hayes
Geoff Hayes on 30 Sep 2016
Tyler - in your countValue function, how do you distinguish between the two vectors (from your example)? Do you concatenate one with the other to create one array (the dataArray input)? Or will you be creating a matrix (assuming each vector has the same number of elements)?
If you are calling this function for each array, then what you can do is once you have found an element that matches the value, then just set count to one and break out of the for loop as
if dataArray(i) == value
count = 1;
break;
end
Or avoid the loop and just use find or ismember to see if your value is in the dataArray.

Sign in to comment.

Accepted Answer

dpb
dpb on 30 Sep 2016
Edited: dpb on 30 Sep 2016
Presuming the phrase 'array of vectors' means a 2D "ordinary" array, arrange them by column and then the answer is simply
ix=any(ismember(y,value));
Oh, that's the location of which vectors contain the wanted value and you wanted to know how many. Probably returning the above as an optional argument will turn out to be useful enhancement, but the answer you asked for is
n=sum(any(ismember(y,value)));
or, if do choose to return the index array,
n=sum(ix); % to save doing the work twice't

More Answers (0)

Community Treasure Hunt

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

Start Hunting!