# Compare vector to two other vectors

4 visualizzazioni (ultimi 30 giorni)
DucciVinci il 9 Mar 2023
Risposto: DucciVinci il 9 Mar 2023
I'm struggling with the following binning task:
I have three vectors of different sizes k, m and n. My goal is to get an -matrix in which the -th entry simply counts how many elements from the k-vector are simultaneously smaller than both and .
So basically I want to do something like but with one of the inputs as a matrix rather than a vector.
Is there an efficient way to do this?
Of course I can and have also done it with a loop, but that seems terribly inefficient especially since the k from my simplified example is actually really large. Trying to write everything in -Matrices results in too large arrays unfortunately.
##### 1 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
Dyuman Joshi il 9 Mar 2023
"Of course I can and have also done it with a loop..."
Can you show what have you tried?

Accedi per commentare.

### Risposta accettata

DucciVinci il 9 Mar 2023
Ah I'm sorry, I completely forgot about matrix multiplication.
Solution actually is pretty simple:
Transpose the k-vector and compare with both other vectors using implicit Cartesian expansions, giving logical arrays of sizes and .
Now just transpose the -matrix and multiply, killing the k-dimension.
Not quite used to matrix multiplication with logical arrays, but it makes a lot of sense here.
Sorry to have bothered you.
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Più risposte (2)

David Hill il 9 Mar 2023
m=randi(100,1,20);
n=randi(100,1,30);
k=randi(100,1,10000);
[M,N]=meshgrid(m,n);
x=min(M,N);
z=zeros(size(x));
u=unique(x);
y=sum(k<u,2);
for j=1:length(u)
z(x==u(j))=y(j);
end
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Steven Lord il 9 Mar 2023
I think what you want is to use histcounts2 to calculate how many numbers fall into each bin between m(k) and m(k+1) [and between n(k) and n(k+1)] then call cumsum twice, once to sum across the rows and once to sum the matrix from the previous call down the columns.
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Categorie

Scopri di più su Matrix Indexing in Help Center e File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by