user input and calling subfunction

8 views (last 30 days)
Abdulelah  Jo
Abdulelah Jo on 28 Nov 2018
Commented: Guillaume on 28 Nov 2018
i have defined the following two functions to calculate the area and length of triangle which has 3 points (a,b,c). so i should prompt the user to entre the coordinates of each point (x1,y1 x2,y2 x3,y3) & call my functions . shall i do that in a seperate script ?
function [Area] = findArea(s,a,b,c)
Area = sqrt(s*(s-a)*(s-b)*(s-c));
findLength()
end
--
function [Distance] = findLength(x1,x2,y1,y2)
Distance=sqrt((x1-x2).^2 + (y1-y2).^2);
end
  1 Comment
Guillaume
Guillaume on 28 Nov 2018
I have no idea why you're calling findLength inside findArea but calling findLength without any input arguments as you have done is going to result in an error, and calling findLength without any output is kind of pointless.
You would use findLength with for example:
coords = input('enter a 4 element vector of the form [x1, x2, y1, y2]');
assert(numel(coords) == 4, 'you didn''t enter a 4 element vector');
distance = findLength(coords(1), coords(2), coords(3), coords(4));
fprintf('the distance between the points is %g\n\n', distance);

Sign in to comment.

Answers (1)

Adam Danz
Adam Danz on 28 Nov 2018
Edited: Adam Danz on 28 Nov 2018
It's entirely up to you how you'd like to organize your code. If you think your length and area functions might someday be needed for different analyses, you might want them to be independent functions.
If they are unique to this analysis, you could include them as nested fuctions within your main function (or local functions within a script). See those links for examples.
I think the decision should be based on whether or not other functions will need access to those functions in the future.

Community Treasure Hunt

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

Start Hunting!