0

In the Matlab Anonymous Functions, I want to have Functions fun_total like this

fun_total = @(x) [ 0;
               1*x(1);
               1*x(1);
               2*x(2);
               2*x(2);
               ...
               100000*x(100000);
               100000*x(100000);]

so here is my code

fun_total = @(x) [0];
for i = 1 : 100000
  fun_temp = @(x) i*x(i);
  fun_total = @(x) [ fun_total(x); fun_temp(x) ];
  fun_total = @(x) [ fun_total(x); fun_temp(x) ];
end

My problem is it's too slow when loop iteration become bigger. Every time fun_total = @(x) [ fun_total(x); fun_temp(x) ];
The fun_total(x) will expand first ,and then merge.

Now I have a solution is output my fun_total as a text file, and then change to function. Is this can work? or someone have other efficient solution? Thanks!!

2 Answers 2

3

The problem obviously is, that you are generating 100000 anonymous functions fun_temp (and 100000 nested functions fun_total). This is essentially the same as generating all the m-file-functions function result=xTimes1(x), function result=xTimes2(x), function result=xTimes3(x),... Which when you look at it that way is totally absurd. The best solution is certainly going with a vectorized solution like Dan's, but you can also always consider using a single m-function file.

In terms of efficiency you should expect this hierarchy:

Lots of (anonymous) function calls < lots of for-loop iterations < vectorized code.

So as an intermediate step to the vectorized solution you could use:

function total = fun_total(x)
total = zeros(2*length(x)+1,1);
for i = 1:length(x)
    total([2*i,2*i+1]) = [i*x(i); i*x(i)];
end

and then generate the function handle using @fun_total.

Sign up to request clarification or add additional context in comments.

1 Comment

specially for the hierarchy: +1
2

Maybe try:

fun_total = @(x)reshape(repmat(1:numel(x).*x, 2, 1),[],1)

or

fun_total = @(x)reshape([1;1]*(1:numel(x).*x),[],1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.