iterate over single array dimension
Mostrar comentarios más antiguos
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?
2 comentarios
Guillaume
el 24 de Sept. de 2019
As far as I know the behaviour of bsxfun has not changed at all since implicit expansion was introduced. Your usage of bsxfun doesn't make much sense, you've got an anonymous function with two inputs, x and y, but it doesn't use y. And since you're passing twice the same input, there's obviously no expansion to be done. So your equation reduces to (regardless of version):
quadraticRoots = roots(data);
which obviously doesn't work with matrices.
G Smith
el 24 de Sept. de 2019
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!