1
votes

I have a function in Matlab:

function [runs,balls]=batting(form,team_flag,weather_flag)

form is a 1x13 array of doubles. The flags are just boolean. runs,balls are just scalars. The function above does some complex mathematical simulation to arrive at its output values. Now i write a wrapper :

function [runs,balls]=wrapper1(form)
[runs,balls]=batting(form,false,false);

Then I write another wrapper:

function runs_vector=wrapper2(form_vector)
for i=1:size(form_vector,1)
    form_cell{i}=form_vector(i,:);
end
runs_vector=cellfun(@wrapper1, form_cell)';

It must be evident as to what i am trying to achieve. I am trying to exploit the behavior of cellfun for my custom-defined function batting. The flag arguments need to be set to false here but in general they are varied in the project of which this is part of. So i could not disappear the flag inputs to the batting function without writing an intermediate wrapper,i.e. wrapper1. My question is if there is a less ugly or more smart way of doing this?

1
You should modify batting, such that it takes a n x 13 matrix as input, which makes both wrappers obsolete.hbaderts
But the thing is that the complex mathematical simulation is the function batting which takes a 1x13 vector. Generalizing it for nx13 matrix would require to run a for loop n times in the batting function. Rather i have done so using the wrappers. And this seems more elegant than the for loop method. I want to keep the complex math sim as a separate blackbox which i don't want to peep into let alone modify!user_1_1_1
Note that cellfun (and all the *funs) is slower than the explicit loop in almost all cases.excaza

1 Answers

2
votes

You can eliminate wrapper1 by creating an anonymous function that reduces batting to two arguments:

runs_vector = cellfun(@(form) batting(form, false, false), form_cell)';

In addition, the loop can be replaced by num2cell like so:

form_cell = num2cell(form_vector, 2);

Combining these two gives us

function runs_vector = wrapper2(form_vector)
form_cell = num2cell(form_vector, 2);
runs_vector = cellfun(@(form) batting(form, false, false), form_cell)';