Effacer les filtres
Effacer les filtres

How to create a function with multiple calculations

13 vues (au cours des 30 derniers jours)
Oskar
Oskar le 15 Déc 2017
Commenté : Tony le 24 Août 2022
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));

Réponse acceptée

YT
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
mahroo shiranzaei
mahroo shiranzaei le 29 Oct 2021
Hello and thanks for the great explanation.
Tony
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?

Connectez-vous pour commenter.

Plus de réponses (1)

James Tursa
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.

Catégories

En savoir plus sur Read, Write, and Modify Image 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!

Translated by