 # Insert new values into vector using indices found by ismember

Code (script file ‘pcolor_fail_test’) to reproduce my problem is:-

``````min_val = 0.8509 ;
max_val = 0.8641 ;
tick_size = 0.0001 ;

y_ax = zeros( 1 , 133 ) ;
y_ax( 1 ) = min_val ;
for ii = 2 : 133
y_ax( ii ) = y_ax( ii - 1 ) + tick_size ;
endfor
y_ax = floor( y_ax ./ tick_size .+ tick_size ) .* tick_size ;
y_ax_copy = zeros( size( y_ax ) ) ;

unique_vols = [ 2 , 3 , 2 , 18 , 3 ] ;

unique_prices = [ 0.8575 , 0.8576 , 0.8578 , 0.8579 ,0.858 ]

TF = find( ismember( y_ax' , unique_prices' ) ) ;
y_ax_copy( 1 , TF ) = unique_vols ;
``````

where the last line gives the error

``````error: =: nonconformant arguments (op1 is 1x4, op2 is 1x5)
error: called from
pcolor_fail_test at line 18 column 21
``````

What I’m trying to do is insert unique_vols into y_ax_copy at the indices given by TF. The problem seems to be that the indices TF are 67 68 70 71 but I expected them to be 67 68 70 71 72.

Checking floating values for equality is bad style.

``````octave:19> format bit
octave:20> y_ax(72)
ans = 0011111111101011011101001011110001101010011111101111100111011100
octave:21> unique_prices(5)
ans = 0011111111101011011101001011110001101010011111101111100111011011
octave:22> format long
octave:23> unique_prices(5)
ans = 0.858000000000000
octave:24> y_ax(72)
ans = 0.858000000000000
``````

Working with floating point numbers is tricky sometimes.
In general, it is best to avoid exact comparisons of floating point numbers. E.g. contrary to intuition, the following compares false:

``````0.1+0.2==0.3
``````

Instead, try and compare against small differences:

``````abs((0.1+0.2) - 0.3) < 10*eps()
``````
1 Like

With a bit of googlefoo I have found a solution thus

``````[ i , j ] = find( abs( bsxfun( @minus , y_ax' , unique_prices ) ) <= tol ) ;
``````

which seems to do the job without the errors caused by comparing float values.

The below pages helped me with this.

2 Likes