How to create a function with multiple calculations
24 ビュー (過去 30 日間)
古いコメントを表示
I have matlab code with 3 different calculations and I am unsure how to put it into a function (I want to solve the code using a function rather than have the calculations embedded in the code.)
a = sqrt((x1-x2)^2+(y1-y2)^2);
b = sqrt((x2-x3)^2+(y2-y3)^2);
c = sqrt((x1-x3)^2+(y1-y3)^2);
s=(a+b+c)/2;
k=sqrt(s.*(s-a).*(s-b).*(s-c));
0 件のコメント
採用された回答
YT
2017 年 12 月 15 日
編集済み: YT
2017 年 12 月 15 日
So I think you're looking for something like this
function [k] = myawesomefunction(x1,x2,x3,y1,y2,y3)
%MYAWESOMEFUNCTION with 6 input arguments x1, x2, x3, y1, y2, y3 and 1
%output argument k
a = sqrt((x1-x2)^2+(y1-y2)^2); b = sqrt((x2-x3)^2+(y2-y3)^2); c = sqrt((x1-x3)^2+(y1-y3)^2);
s=(a+b+c)/2;
k=sqrt(s.*(s-a).*(s-b).*(s-c));
end
If you also want the other variables a, b, c and s, you can just change it to this
function [a, b, c, s, k] = myawesomefunction(x1,x2,x3,y1,y2,y3)
You need to save the file with the same name as you gave the function, so in this case save it as 'myawesomefunction.m'
You can call your function in your main file like so:
myoutputK = myawesomefunction(12,23,45,56,78,91); %if you only have 1 output argument
[outputA,outputB,outputC,ouputS,outputK] = myawesomefunction(12,23,45,56,78,91); %if you have more than 1 output
3 件のコメント
Tony
2022 年 8 月 24 日
but if you are using myawesomefunction as a function from file in the problem-based Optimize live editor, outputB/outputC/outputS/outputK will not be considered in the problem. How to overcome this issue if I really would like to combine all my constraints in one function file?
その他の回答 (1 件)
James Tursa
2017 年 12 月 15 日
編集済み: James Tursa
2017 年 12 月 15 日
Create a file called triangle_area.m on your path (e.g. in your working directory) and inside that function have this code:
% Put a description of the function here with purpose, syntax, etc.
function k = triangle_area(x1,y1,x2,y2,x3,y3)
% insert your calculation code here
end
You might consider changing your side distance formulas so they are vectorized for arrays of x1, y1, etc. E.g.,
a = sqrt((x1-x2).^2+(y1-y2).^2);
etc.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Filter Banks についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!