MATLAB: Iterate over single array dimension

array functionbsxfunimplicit expansionMATLABsingleton expansion

I am having trouble iterating over a single array dimension. For instance, let's say I have a dozen sets of data, and for each dataset I want to solve the quadratic equation. The polynomial coefficient list for all datasets is stored in a single 2D array with dimensions [12,3].
data = randn(12,3);
For a single set of 3 coefficients, I can use the roots function to get the two roots to the equation. How can I iterate over all 12 datasets? Do I need to write a 'for' loop?
In the past, I used the bsxfun something like the following:
quadraticRoots = bsxfun(@(x,y)roots(x), data, data);
In the days before implicit expansion, this would give me an output array with dimensions [12,2] which is what I want. There are two roots for each of the 12 datasets. With the updates to bsxfun, I get a message that the input must be a vector. Instead of single-dimension expansion, bsxfun implicitly expands everything! Arrayfun is no help because it also implicitly expands each element in the 2D array.
The above case is relatively simple, but I do this type of operation very frequently. I have a list of vectors stored as a 2D array, and want to apply a function to each row or column in the list. Is there a general way to iterate over a single array dimension without a 'for' loop?

Best Answer

You can do it with arrayfun for example
coef = randn(12,3)
qroots = cell2mat(arrayfun(@(n) roots(coef(n,:)),1:size(coef,1),'UniformOutput',false))
This returns a 2 by 12 array of roots, one column for each row of coef. You could of course transpose it if you wanted.
This seems quite arcane though. I don't know if there is any performance advantage of doing it this way rather than just putting it in a loop. Certainly a little loop would be more readable. Maybe someone know how to do this in a cleaner way.