Say I have a function calculateStuff(x) that takes in a scalar as parameter and returns a scalar.
Say I have a vector X and I want to apply calculateStuff on every component in X, and get a vector of the results in return and store it in a new vector Y.
Clearly Y=calculateStuff(X) is illegal, is there a way I can do this besides looping?
B = arrayfun( func , A ) applies the function func to the elements of A , one element at a time. arrayfun then concatenates the outputs from func into the output array B , so that for the i th element of A , B(i) = func(A(i)) .
Yes, because all variables are arrays in MATLAB: even scalar values are just 1x1 arrays, so there is absolutely no difference in how they get passed to functions.
B = all( A , 'all' ) tests over all elements of A . This syntax is valid for MATLAB® versions R2018b and later. B = all( A , dim ) tests elements along dimension dim . The dim input is a positive integer scalar.
You have three options:
calculateStuff
so that it can take arrays and return arraysarrayfun
to hide the loop: Y = arrayfun(@calculateStuff,X)
Most Matlab operations will let you input a matrix and return a matrix. You should be able to re-write calculateStuff() to take a matrix and return a matrix. That is generally MUCH faster than using a for loop. Loops in Matlab are very expensive time-wise.
The sorts of things you need to look at are "dot" versions of normal operations. For example instead of
y = z * x;
do
y = z .* x;
The first will do a matrix multiplication, which is probably not what you want when vectorizing code. The second does an element-by-element multiplication of z and x.
See here and search for "The dot operations".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With