I have an optimization problem in MATLAB and I'd like to be able to write an anonymous function to pass to the optimization function.
The function I am minimizing is a function of x, but I am required to pass it y where
y = zeros(N,1);
y(idx) = x;
That is I am passing a vector y that is zero apart from at indexes idx where it is x and x is the variable I am optimizing over.
The key step is the assignment y(idx)=x which is tricky because assignments can't be done in an anonymous function.
I need to do this as efficiently as possible (N and idx will be large.)
I have an anonymous function that works as follows
iif = @(varargin) varargin{2 * find([varargin{1:2:end}], 1, 'first')}();
y = arrayfun(@(k) iif(ismember(k,idx),x(idx==k),true,0),0:N-1)';
but it is slow compared to writing a simple external function.
Now I can use the simple external function, but would like to know if I am missing a trick to make a faster anonymous function.
Edited to add a more complete example.
N = 100;
idx = [2 7 9]';
x = rand(size(idx));
y = zeros(N,1);
y(idx) = x;