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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by