Optimizing indirect mapping: From matrix elements to vector values

7 visualizaciones (últimos 30 días)
dor Levi
dor Levi el 12 de Jun. de 2018
Editada: dpb el 13 de Jun. de 2018
I have a 2-D matrix of values, M. There are also two vectors:
  • Grid - holds values which are close to the values in M. The values in Grid are essentially "the same" values in M, just might be slightly different (by 0.001 for example).
  • Density - For each value of Grid, there is a corresponding density value.
For each element in the matrix: I need to find its density based on the closest value in Grid.
The following code achieves that, but is slow:
function [ density ] = get_density(x, Density, Grid)
[~, min_diff_idx] = min( abs( x - Grid ) );
density = Density( min_diff_idx );
end
M_new = arrayfun( @(x) get_density(x, Density, Grid), M);
Idea for improvement ?
  2 comentarios
dpb
dpb el 12 de Jun. de 2018
Editada: dpb el 12 de Jun. de 2018
  1. Are values in Grid unique?
  2. Are Grid and Density fixed with just lookup from M varying?
  3. Is location in Grid significant or simply the nearest value?
dor Levi
dor Levi el 12 de Jun. de 2018
1. Yes, values in Grid are unique.
2. (Maybe I don't understand the question, but ) Grid and Density stay with the same values throughout the execution.
3. The nearest element value of Grid is important. The index of Grid isn't significant.

Iniciar sesión para comentar.

Respuesta aceptada

dpb
dpb el 12 de Jun. de 2018
Editada: dpb el 13 de Jun. de 2018
OK, with the additional information, remove the 2D nature and use interp1
function density = get_density(x, Density, Grid)
persistent D G % save the 1D values for reuse
if ~isfinite(x) & ~isempty(G), clear D G, return, end % reset persistents
if isempty(G) % initialization
[G,ix]=sort(Grid(:)); % interp1 requires ordered independent variable
D=Density(ix); % put associated dependent variable in same sequence
end
density=interp1(G,D,x,'nearest'); % look up nearest based on input
end
Treat the extrapolation as desired; see documentation for further details on interp1
To use, once called initially with all three arguments, only need to call with an x value or array of values.
If want to reset the persistent variables to use a different table; then call with
get_density(inf)
then use the three-argument form with the new table values.

Más respuestas (0)

Categorías

Más información sobre Optimization Analysis en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by