How to write a function equation in matlab?

조회 수: 3 (최근 30일)
Jim
Jim 2016년 11월 21일
답변: James Tursa 2016년 11월 21일
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