How to apply a multivariate function to each element of a vector?

4 ビュー (過去 30 日間)
Camilo A.
Camilo A. 2016 年 10 月 27 日
回答済み: Andrei Bobrov 2016 年 10 月 28 日
This is not the real function I have problem with. But this one a good example of the problem I have.
function [Y] = testf(a,b,c,X)
Y=dot([a b],[c X]);
end
a,b,c,d are previously determined scalar variables (real) and X a vector.
E.g.:
a=1; b=2; c=3; X=[-10:1:10];
I want to evaluate function f to each element of X keeping a,b,c constant.
Something like this... But for X more generally.
[testf(a,b,c,-10) testf(a,b,c,-9) testf(a,b,c,-8) ...]
Here is an example:
>> a=1; b=2; c=3; X=[-10:1:10];
>> testf(a,b,c,X)
Error using dot (line 33)
A and B must be same size.
Error in testf (line 2)
Y=dot([a b],[c X]);
I know where the error is, but any solution to this?

採用された回答

James Tursa
James Tursa 2016 年 10 月 28 日
Something like this?
a=1; b=2; c=3; X=[-10:1:10];
fun = @(x) testf(a,b,c,x);
Y = arrayfun(fun,X);

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2016 年 10 月 28 日
>> a=1; b=2; c=3; X=-10:10
X =
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10
>> testf = @(a,b,c,X)[a b]*[repmat(c,1,numel(X));X(:)'];
>> testf(a,b,c,X)
ans =
-17 -15 -13 -11 -9 -7 -5 -3 -1 1 3 5 7 9 11 13 15 17 19 21 23
>>

カテゴリ

Help Center および File ExchangeReporting and Database Access についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by