if i have A=[3 4 5 6] and B=[6 5 4] then i want to compare each value in A with all values in B, if this value is greater then increase counter with 1 and if this value is equal then increase another counter with 1
Comparison between vectors in matlab
93 views Asked by Asmaa Daoud At
2
There are 2 answers
0
On
Another approach in comparison to arrayfun
would be bsxfun
. Though it takes a bit more memory, I'd argue that it's faster. arrayfun
is implicitly a for
loop and using loops in MATLAB is usually slower than vectorized approaches.
If you want the greater than case, use the gt
function with bsxfun
, so:
>> A = [3 4 5 6];
>> B = [6 5 4];
>> sum(bsxfun(@gt, A, B.'), 1)
ans =
0 0 1 2
If you want to accumulate all of the values that match the criterion, you can put another sum
call within this bsxfun
call:
>> sum(sum(bsxfun(@gt, A, B.'), 1))
ans =
3
For the greater than or equal case, use ge
:
>> sum(bsxfun(@ge, A, B.'), 1)
ans =
0 1 2 3
For the equality case, use eq
:
>> sum(bsxfun(@eq, A, B.'), 1)
ans =
0 1 1 1
Again, if you want to accumulate all of the values that match the criterion, nest another sum
call with the above results.
If you want an array that corresponds to the result of each value in
A
, you could dothis gives
[0, 0, 1, 2]
. If you want the total sum you would just putsum(...)
around that:this gives
3
.For the equal-counter, you can simply change
>
to==
:this gives
[0, 1, 1, 1]
.