Anonymous Functions for updating arrays.

3 views (last 30 days)
I use many anonymous functions for updating elements within arrays. However generally this requires me to write this kind of thing:
Anew = A;
Anew(i) = anon_f(A,i);
However I feel it should be possible to redefine the function so that all I need is:
Anew = anon_f2(A,i);
Of course, I could always just use child functions instead... An example function:
f = @(state,i)(2*ceil(rem(sum(state(:,i).^3),1)) - 1);

Accepted Answer

Walter Roberson
Walter Roberson on 29 Jun 2013
anon_f2 = @(Variable,idx) subsasgn(Variable, struct('type','()','subs',{{idx}}), anon_f(Variable,idx));
Note that your preferred syntax expects the index to not only select which output location is used but also forms one of the arguments into anon_f to choose the proper output value. I can't quite picture a case in which that would be useful ?
  4 Comments
Chris
Chris on 29 Jun 2013
Sorry - mis-typed above, should be Anew(i,i) = ...I think that solves most of those issues. As to why I only want to update the values on the diagonal...I don't want to explain the whole problem. Thanks again.
Walter Roberson
Walter Roberson on 29 Jun 2013
Ah. To change (i,i) make the 'subs' into {{idx, idx}}

Sign in to comment.

More Answers (0)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!