MATLAB: How to sum logical relations between elements of a vector

for looplogical?MATLABsumwhile

I have the following problem: I need to sum logical all the logical relations of this vector:
x= [1 2 3].
The result must be:
res=(x(1)>x(2))+(x(1)>x(3))+(x(2)>x(3))+(x(2)>x(1))+(x(3)>x(1))+(x(3)>x(2));
In other words, res=3. I have the following code:
x = [1 2 3]; % Test Array
sumx2=0
k = 1; % Add Counter Variable
j=1;
while j<=length(x)
while k<=length(x)
sumx2=sumx2+(x(k)>x(j));
k=k+1;
end
j=j+1;
end
In this case the value of sumx2 is 2. I don't know what is wrong with the code. Please, help me.

Best Answer

You can use bsxfun to do this quite easily:
>> x = [1,2,3];
>> tmp = bsxfun(@gt,x,x(:));
>> sum(tmp(:))
ans = 3