Azzera filtri
Azzera filtri

How to create a function with multiple calculations

13 visualizzazioni (ultimi 30 giorni)
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));

Risposta accettata

YT
YT il 15 Dic 2017
Modificato: YT il 15 Dic 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 Commenti
mahroo shiranzaei
mahroo shiranzaei il 29 Ott 2021
Hello and thanks for the great explanation.
Tony
Tony il 24 Ago 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?

Accedi per commentare.

Più risposte (1)

James Tursa
James Tursa il 15 Dic 2017
Modificato: James Tursa il 15 Dic 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.

Categorie

Scopri di più su Read, Write, and Modify Image in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by