How to vectorize for-loop for anonymous function that takes in row vectors as inputs, and spits out a single number as output.
2 views (last 30 days)
Show older comments
Muhammad Asif
on 24 May 2017
Answered: Michelangelo Ricciulli
on 24 May 2017
The anonymous function is for instance
%n-variable Schwefel function %MULTI-MODAL
% From https://www.sfu.ca/~ssurjano/schwef.html
func = @(X) 418.9829*length(X)-sum(X.*(sin(sqrt(abs(X))))
It is built in a way such that it can accept a row vector of any size and return a single output.
My overall script accepts an m-by-n matrix (inData) as the input matrix, where each row is a specific row input to test, and m is the number of inputs.
The output should be a m-by-1 output vector(outVal) where each row is the function evaluation output of the corresponding row in Matrix A.
Here is a non-vectorized version of this operation:
outVal = zeros(length(inData(:,1)),1);
for i=1:length(inData(:,1))
outVal(i,1) = func(inData(i,:));
end
I would appreciate it if anyone can offer me some guidance on how to perform this operation in a vectorized manner, without changing the ability of the input function to accept an input of arbitrary row size. Thanks.
0 Comments
Accepted Answer
Michelangelo Ricciulli
on 24 May 2017
Hi, I think that you need just to slightly modify your function func. Let's say it accepts only ROW vectors like
a=[1, 2, 3, 4, 5];
Then you can add an argument to sum, to specify that it performs the sum over the row, and use the function "size" instead of length to count the number of elements (not really needed if you just have a vector and not a matrix)
func = @(X) 418.9829*size(X,2)-sum(X.*(sin(sqrt(abs(X)))),2);
In this way your function will work perfectly also for a matrix and will act the way you want on each row.
0 Comments
More Answers (0)
See Also
Categories
Find more on Multidimensional Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!