How to use a function file in a 'for loop'?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I'm supposed to write a function of a polygon "train". It's several dots on a graph that are connected with lines between. I get the length of the "train" to be
n=length(x);
L=0;
for i=1:n-1
L=L+sqrt((x(i+1)-x(i))^2+(y(i+1)-y(i))^2);
end
L
however, I need to write a function file and I'm confused. How do I put the function file in the loop? Of what I can understand, I need to make a function file where define the equation, then make a for loop file and somehow make a command so that it uses the function file and calculates the lenght of the damn polygon. Am I on the right track guys?
3 commentaires
dpb
le 1 Oct 2013
Your English is quite good albeit perhaps some vocabulary is missing... :)
Syntax is the general set of rules by which source code is interpreted. What is expected to be the form of inputs and the resulting outputs for a given expression, in other words.
By "example syntax" I simply meant an example of some code that illustrated (was an example of) a particular usage. In this case, the calling of a function.
On the structuring of Matlab code -- firstly again I urge you to work thru the initial sections of the documentation following their examples that illustrate the points.
But, Matlab is somewhat different from most other programming languages in that a function is associated one-to-one with the m-file of the same name that holds the source code for the function (setting aside for the moment internal functions and other more advanced constructs). Hence, for each function you write there will be an m-file and the code that uses that function (whether a script or another function) will be (in a higher-level organizationally in the logic) contained in its own file.
Whether the for...end loop is in the function or the higher-level function calls the function in a loop is dependent on the choice of implementation. In your example above you can write the function that does the summation in the loop and returns the result; there's no need to have each term computed by itself and then call that single line as a function in a loop.
Those decisions of what to include in a given function are known as "factorization" of the overall code.
Hopefully that'll help more than further obfuscate... :)
Réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements 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!