How to create a function with multiple calculations
18 次查看(过去 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!