How to write a function equation in matlab?

3 views (last 30 days)
Hello, I'm having trouble on how to write this function (see insert image) into Matlab. It seems like a basic question, but I'm unsure. Any help would be great.
I have an general idea how to write it in matlab, but I'm not sure if this is correct.
func_l = c*exp(1/pi)*(x - A)^2 * cos*(pi*(x - A)^2);
  4 Comments
James Tursa
James Tursa on 21 Nov 2016
You have ranges on both x1 and x2. Does that mean this is supposed to generate a surface plot?
Jim
Jim on 21 Nov 2016
Yes. But I'm not sure how to correctly write the " Given function" into Matlab. Like how to input the written formula into the Matlab language.

Sign in to comment.

Accepted Answer

James Tursa
James Tursa on 21 Nov 2016
Here is a function assuming single values for x1 and x2, which would be stored in the vector x:
% Assumes numel(c)==size(A,1) and numel(x)==size(A,2)
function result = fl(A,c,x)
x = reshape(x,1,[]); % make sure x is a row vector
c = c(:); % make sure c is a column vector
y = sum(bsxfun(@minus,x,A).^2,2); % the sum over j part
result = sum(c .* exp((-1/pi)*y) .* cos(pi*y)); % the sum over i part
end
To call it for multiple values of x1 and x2 you could use loops. E.g.,
x1 = 0:.01:10;
x2 = 0:.01:10;
c = [1 2 5 2 3];
A = [3 5;5 2;2 1;1 4;7 9];
z = zeros(numel(x1),numel(x2));
for m=1:numel(x1)
for n=1:numel(x2)
z(m,n) = fl(A,c,[x1(m) x2(n)]);
end
end
surf(x1,x2,z,'LineStyle','none');
There are ways to vectorize the fl function to allow for multiple x1's and x2's per call (speed and convenience), but I did not go that far with my example code.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!