I have a matrix of structs:
s(1:2,1:3) = struct('a',1,'b',2);
I have a function that has 2 int inputs, and calculates an int values according
to some logic. How can I Apply the function on all the matrix s using the fields of each struct (‘a’ and ‘b’) as input for the function. The result matrix should be the same size as s just with the result of the function as data.
function f = SomeFunctionIWrote(a,b)
%...Some calculations...
f = result;
end
Thanks,
Guy.
Applying the same function to each element of an array is what arrayfun is built for (see this blog post by Loren Shure for a helpful discussion/example).
If
fis your function andsis an array of structures with fieldsaandb,will do the trick.
@(x)is an anonymous function if you haven’t come across those before.If the function doesn’t return a scalar, use the
'uniformoutput'option (set tofalse) so thatresultbecomes a cell array.Note 1:
arrayfunis slow! Often (always?) slower than a loop. The advantage of it (in my experience/opinion) comes from not having to deal with size/shape of matrix dimensions if/when your code changes, and shorter code that is easier to read.Note 2: you can use
'uni'and0in place of'uniformoutput'andfalseto save typing/line space, though at the expense of clarity