How to apply a multivariate function to each element of a vector?
3 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
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);
0 个评论
更多回答(1 个)
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
>>
0 个评论
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!