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

조회 수: 2 (최근 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 CenterFile Exchange에서 Reporting and Database Access에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by