user input and calling subfunction

8 次查看(过去 30 天)
Abdulelah  Jo
Abdulelah Jo 2018-11-28
评论: Guillaume 2018-11-28
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 个评论
Guillaume
Guillaume 2018-11-28
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);

请先登录,再进行评论。

回答(1 个)

Adam Danz
Adam Danz 2018-11-28
编辑:Adam Danz 2018-11-28
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.

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by