Anonymous Functions for updating arrays.

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);

 Réponse acceptée

Walter Roberson
Walter Roberson le 29 Juin 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 commentaires

Thanks, this works - I didn't know about the subsasgn function.
I'm not sure I understand your comment though. I guess you're pointing out that, (at least it works for the function f above) I could redefine it so that instead:
anon_f2 = @(Variable,idx) subsasgn(Variable, struct('type','()','subs',{{idx}}), anon_f(Variable(:,idx)));
I guess this is a little neater.
Walter Roberson
Walter Roberson le 29 Juin 2013
Your index appears to be a linear index for the purpose of the assignment, but you are using it as a column selector of the variable for the purpose of the anonymous function. I do see in your sample routine with the rem() and sum() calls that Yes, you extract a column and produce a single value, but:
(A) If the output is the same for all values in the same column, then why is the output only assigned to a single value instead of to a column ?
(B) Are you sure that you want to select a column from the variable but then assign to the row of the same number, since linear indexing goes down rows? If ANew = A; ANew(3) = sum(A(:,3)) then the ANew(3) means ANew(3,1) not some slot in the third column.
(C) Watch out for non-square A, different number of rows and columns is going to mess you up...
Chris
Chris le 29 Juin 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 le 29 Juin 2013
Ah. To change (i,i) make the 'subs' into {{idx, idx}}

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by