compare Vector and matrix

Hi. Say I have a column vector A and matrix B as A=[1.5 5.5 9.5]' and B=[ 1 2 3; 4 5 6; 7 8 9]. I would like to write a code that compares the first element of A, A(1,1)=1.5, with the first row of B and tells me the position of this number with respect to the fist row. For this example as B(1,1)<A(1,1)<B(1,2) it passes me 1, and 0 otherwise. Then for the second element A(2,1) it should passes 1 to me at B(2,2)<A(2,1)<B(2,3) and zero otherwise. Then for A(3,1) just passed me 1 at A(3,1)>B(3,3) and zero otherwise. I want the code to passes me a position test matrix as test=[0 1 0 0;0 0 1 0;0 0 0 1]. I know that I can do this with for loops but I was wondering if there is an easier way for it too. Thanks a lot!

Réponses (1)

Roger Stafford
Roger Stafford le 15 Avr 2016

0 votes

n = size(B,1);
B0 = [-Inf(n,1),B];
B1 = [B,Inf(n,1)];
A1 = repmat(A,1,size(B,2)+1);
test = double((B0<A1)&(A1<B1));

Catégories

En savoir plus sur MATLAB dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by