I have a problem with the nested function.
3 次查看(过去 30 天)
显示 更早的评论
I need to write a function which gives the area of a triangle and in it a subfunction that calculates the distance between each point of the triangle (I need it for the area). My program doesn't work can someone let me know what I am doing wrong pls?
Here is my program:
x1=input('Enter the x coordinate of the first point ');
y1=input('Enter the y coordinate of the first point ');
x2=input('Enter the x coordinate of the second point ');
y2=input('Enter the y coordinate of the second point ');
x3=input('Enter the x coordinate of the third point ');
y3=input('Enter the y coordinate of the third point ');
s=(a+b+c)/3;
fprintf('The area of the triangle is %.2f\n',area)
end
and here is my function with the nested subfunction:
function [area]=calcarea(a,b,c,s)
function [a,b,c]=dist(x1,x2,x3,y1,y2,y3)
a=sqrt((x1-x2)^2 + (y1-y2)^2);
b=sqrt((x1-x3)^2 + (y1-y3)^2);
c=sqrt((x2-x3)^2 + (y2-y3)^2);
end
area=sqrt(s*(s-a)*(s-b)*(s-c));
end
0 个评论
采纳的回答
madhan ravi
2018-11-8
编辑:madhan ravi
2018-11-8
Multiple functions way:
x1=input('Enter the x coordinate of the first point ');
y1=input('Enter the y coordinate of the first point ');
x2=input('Enter the x coordinate of the second point ');
y2=input('Enter the y coordinate of the second point ');
x3=input('Enter the x coordinate of the third point ');
y3=input('Enter the y coordinate of the third point ');
[a,b,c]=dist(x1,x2,x3,y1,y2,y3) %first function call
s=(a+b+c)/3;
area=calcarea(a,b,c,s) %second function call
fprintf('The area of the triangle is %.2f\n',area)
function [a,b,c]=dist(x1,x2,x3,y1,y2,y3)
a=sqrt((x1-x2)^2 + (y1-y2)^2);
b=sqrt((x1-x3)^2 + (y1-y3)^2);
c=sqrt((x2-x3)^2 + (y2-y3)^2);
end
function area=calcarea(a,b,c,s)
area=sqrt(s*(s-a)*(s-b)*(s-c));
end
nested function way:
x1=input('Enter the x coordinate of the first point ');
y1=input('Enter the y coordinate of the first point ');
x2=input('Enter the x coordinate of the second point ');
y2=input('Enter the y coordinate of the second point ');
x3=input('Enter the x coordinate of the third point ');
y3=input('Enter the y coordinate of the third point ');
area=calcarea(x1,x2,x3,y1,y2,y3) %parent function call
fprintf('The area of the triangle is %.2f\n',area)
function [area]=calcarea(x1,x2,x3,y1,y2,y3) %parent function
[a,b,c]=dist(x1,x2,x3,y1,y2,y3)
s=(a+b+c)/3;
area=sqrt(s*(s-a)*(s-b)*(s-c));
function [a,b,c]=dist(x1,x2,x3,y1,y2,y3) %nested function
a=sqrt((x1-x2)^2 + (y1-y2)^2);
b=sqrt((x1-x3)^2 + (y1-y3)^2);
c=sqrt((x2-x3)^2 + (y2-y3)^2);
end
end
1 个评论
Hari Ijjada
2019-8-30
if i use multiple function way or nested functions way .By using which function name i should save the function file ?
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 File Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!