tags:

views:

27

answers:

1

Hi, I am having issues manipulating a matrix. Any help would be much appreciated! Say I have a matrix:

xb =

          1.00          2.00          3.00          6.00          5.00          9.00

and another matrix:

cb =

       3000.00       4000.00       4000.00             0             0             0

Is there a way to code something that would check to see if a 1 is within the xb matrix, and display the corresponding cell in cb (the same column that one is)?

so for example, since 6 is in the xb matrix above, the program would display 0. Thanks!

+2  A: 

In one line:

cb(xb==1)

xb==1 creates a logical array of the same size as xb, which is 1 wherever xb is 1, and 0 elsewhere. Since this logical array is of the same size as cb, you can use it for indexing. Indexing an array with a logical array returns all the values of the array at the places where the logical array is 1 (think of it as a mask).

Jonas
@Jonas: you might want to link to these questions regarding floating point comparison: http://stackoverflow.com/questions/2202641/how-do-i-compare-all-elements-of-two-arrays-in-matlab, http://stackoverflow.com/questions/686439/why-is-24-0000-not-equal-to-24-0000-in-matlab
Amro
cb(abs(xb-1)<eps) should take care of floating point errors.
Doresoom

related questions