How to write a function equation in matlab?

12 次查看(过去 30 天)
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 个评论
James Tursa
James Tursa 2016-11-21
You have ranges on both x1 and x2. Does that mean this is supposed to generate a surface plot?
Jim
Jim 2016-11-21
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.

请先登录,再进行评论。

采纳的回答

James Tursa
James Tursa 2016-11-21
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by