How do I count vectors with a specified value in an array of equal length vectors in Matlab?
조회 수: 4 (최근 30일)
이전 댓글 표시
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
Geoff Hayes
2016년 9월 30일
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
채택된 답변
dpb
2016년 9월 30일
편집: dpb
2016년 9월 30일
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
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!