Vlad
Vlad

Reputation: 113

Apply constant-value MATLAB function to array

Assume I generate MATLAB function using symbolic expression, which sometimes can be a constant. For example, if I compute gradient of different curves, one of the vector components can be a number:

syms x y;
expr = x^2 - 4*y;
grad = gradient(expr, [x, y]);

grad_func = matlabFunction(grad, 'Vars', [x, y]);

Assume that I want to apply this to an array of points. Is there a way to make generated MATLAB function robust enough to always return an array of the same size as input, even if original analytical expression (or a certain component of it) was a constant?

I try the following:

X = [-1:0.2:1]; 
Y = [-1:0.2:1];
[Gx, Gy] = grad_func(X,Y);

but get the error:

Error using vertcat

Dimensions of matrices being concatenated are not consistent.

Error in symengine>makeFhandle/@(x,y)[x.*2.0;-4.0]


I also tried to use ARRAYFUN:

[Gx, Gy] = arrayfun(grad_func,X,Y);

but failed as well:

The right hand side of this assignment has too few values to satisfy the left hand side.

Error in symengine>makeFhandle/@(x,y)[x.*2.0;-4.0]

Upvotes: 1

Views: 274

Answers (1)

user1543042
user1543042

Reputation: 3440

Here is how you do the array function

 g = cell2mat(arrayfun(@(x,y) grad_func(x,y), X(:)',Y(:)', 'uni', 0));
 Gx = reshape(g(1, :), size(X));
 Gy = reshape(g(2, :), size(Y));

Upvotes: 2

Related Questions