Inconveniences working with matlabFunction

1 次查看(过去 30 天)
Hello,
I think that I am repeating the same sort of question I bothered you yesterday but I did not expect to run into peoblem again. Consider the following:
>> syms x y
>> g=[x*y y^2;x^3 1-x^2];
>> G=matlabFunction(g)
G =
function_handle with value:
@(x,y)reshape([x.*y,x.^3,y.^2,-x.^2+1.0],[2,2])
I am not happy with this. I would prefer the 'reshape' to be removed. Why? because this is never convenient in letting me to to do vector operations. For instance, if I use the command G([1 1],[1 1]) then matlab throws an erros message. How can I tell matlab PLEASE make the following matlab function for me:
G=(x,y)[x.*y,x.^3,y.^2,-x.^2+1.0];
In my codes G (different G, of course) is the Hessian matrix and I need to use it for my optimization problem in order to get faster and more accurate solutions.
Thanks for your kind help, in advance!
Babak

采纳的回答

Star Strider
Star Strider 2022-9-8
The reshape argument simply takes the vector of argumentsin the square brackets [] and creates a matrix from them, as required. One option is to use arrayfun. However, it wil then interpret its inputs as —
GL([x(1) x(2)],[y(1) y(2)])
So changing the arguments so you and the function agree on how they should be claculated will be necessary, regardless of the funciton version you end up using —
G = @(x,y)reshape([x.*y,x.^3,y.^2,-x.^2+1.0],[2,2]); % 'matlabFunction' Result
GL = @(xv,yv) arrayfun(G, xv,yv, 'Unif',0);
V = GL([1 2],[3 4])
V = 1×2 cell array
{2×2 double} {2×2 double}
V{1}
ans = 2×2
3 9 1 0
V{2}
ans = 2×2
8 16 8 -3
G2 = @(x,y)[x.*y y.^2; x.^3 1-x.^2]; % Your Original Function (Vectorised)
V = G2([1 2],[3 4])
V = 2×4
3 8 9 16 1 8 0 -3
G2L = @(xv,yv) arrayfun(G2, xv,yv, 'Unif',0);
V2 = G2L([1 2],[3 4])
V2 = 1×2 cell array
{2×2 double} {2×2 double}
V2{1}
ans = 2×2
3 9 1 0
V2{2}
ans = 2×2
8 16 8 -3
Both end up producing the same result.
.
  6 个评论

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by