How to create a function with multiple calculations
25 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
YT
le 15 Déc 2017
Modifié(e) : YT
le 15 Déc 2017
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 commentaires
Tony
le 24 Août 2022
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?
Plus de réponses (1)
James Tursa
le 15 Déc 2017
Modifié(e) : James Tursa
le 15 Déc 2017
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 commentaires
Voir également
Catégories
En savoir plus sur Filter Banks dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!