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 日間)
古いコメントを表示
Muhammad Asif
2017 年 5 月 24 日
回答済み: Michelangelo Ricciulli
2017 年 5 月 24 日
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!