Convert a symbolic vector to a list of scalar outputs for a function created by matlabFunction
2 ビュー (過去 30 日間)
古いコメントを表示
When matlabFunction creates an anonymous function, its arguments are always scalars. But when I want to use the function, my data is in vector form. Indeed, when I create the matlab function, I don't know the size of the vector. Is there some way that I can convert an n x 1 vector into n scalars for the purpose of feeding it into my matlab function? Here's an example
syms c1 c2 c3 c4 c5 c6 c7 c8
n = 5;
c = sym('c',[n,1])
f = @(c) prod(c)
jacf= matlabFunction(jacobian(f(c)))
jacf is now a function with arguments c1 ... c5, specifically
jacf =
function_handle with value:
@(c1,c2,c3,c4,c5)reshape([0.0,c3.*c4.*c5,c2.*c4.*c5,c2.*c3.*c5,c2.*c3.*c4,c3.*c4.*c5,0.0,c1.*c4.*c5,c1.*c3.*c5,c1.*c3.*c4,c2.*c4.*c5,c1.*c4.*c5,0.0,c1.*c2.*c5,c1.*c2.*c4,c2.*c3.*c5,c1.*c3.*c5,c1.*c2.*c5,0.0,c1.*c2.*c3,c2.*c3.*c4,c1.*c3.*c4,c1.*c2.*c4,c1.*c2.*c3,0.0],[5,5])
If for example my vector c = 1:5, is there some way I can break it into scalars so that I can compute
jacf(1,2,3,4,5)
Or, better, is there a way I can convert jacf into an anonymous function whose vector argument is [c1,c2,c3,c4,c5]
Thanks for any suggestions!
0 件のコメント
採用された回答
Andrei Bobrov
2018 年 3 月 15 日
編集済み: Andrei Bobrov
2018 年 3 月 16 日
n = 5;
c = sym('c',[n,1]);
jacf= matlabFunction(jacobian(prod(c)),'v',{c});
use
>> c = 1:5;
>> jacf(c(:))
ans =
120 60 40 30 24
or for vectors
function out = jacf(x)
n = numel(x);
out = prod(x(repmat((1:n-1)',1,n) + tril(ones(n-1,n))));
end
or
function out = jacf(x)
n = numel(x);
e1 = eye(n);
out = prod(repmat(x(:),1,n).*~e1 + e1);
end
0 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Code Generation についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!