How to vectorize for-loop for anonymous function that takes in row vectors as inputs, and spits out a single number as output.
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Michelangelo Ricciulli
2017-5-24
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Multidimensional Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!