Pregunta

I want to find out the index of the matrix column in which the vector appears. My idea is to do AND of the vector over matrix and only the column that is the same will be 1 in the new vecotr. But I don't know how to do this. Below is example:

H =
0   0   0   0   1   1   1   1   1   1   1   1   0   0   0
0   1   1   1   0   0   0   1   1   1   1   0   1   0   0
1   0   1   1   0   1   1   0   0   1   1   0   0   1   0
1   1   0   1   1   0   1   0   1   0   1   0   0   0   1

S =
0   1   0   1

From that I want to get 2 as second column or even better vector

0 1 0 0 0 0 ... 0 

Since there is error in second column.

How can I do this in Matlab or even better Octave?

¿Fue útil?

Solución 4

That's pretty easy with broadcasting. The following will require Octave 3.6.0 or later but you can use bsxfun if you have a previous version:

octave-cli-3.8.1> h = logical ([
0   0   0   0   1   1   1   1   1   1   1   1   0   0   0
0   1   1   1   0   0   0   1   1   1   1   0   1   0   0
1   0   1   1   0   1   1   0   0   1   1   0   0   1   0
1   1   0   1   1   0   1   0   1   0   1   0   0   0   1]);
octave-cli-3.8.1> s = logical ([0   1   0   1]');
octave-cli-3.8.1> all (h == s)
ans =

   0   1   0   0   0   0   0   0   0   0   0   0   0   0   0

From here, it's all a matter of using find to get the column numbers. It will even work if it matches more than 1 column:

octave-cli-3.8.1> find (all (h == s))
ans =  2

Otros consejos

Not really sure how you tried to approach the problem. But with repmat or bsxfun it is as simple as this:

all(bsxfun(@eq,H,S'))

How about

result = sum(H==repmat(S(:),[1 size(H,2)]))==4;

I found out the function

ismember(H', S, "rows") 

works exactly as I want. Your answers are all good too, thanks.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top