write a function called tri_area returns the area of a triangle with base b and height h
조회 수: 201 (최근 30일)
이전 댓글 표시
hello this is my function code and command window code and there is a message of invalid expression at line 2 and i dont know what is the wrong can anyone help me
function [area] = tri_area([b,h]);
tri_area([b,h])=(0.5)*(b)*(h)
area=tri_area([b,h])
end
%command window
area = tri_area[3,2])
댓글 수: 16
채택된 답변
Torsten
2020년 4월 9일
편집: darova
2020년 4월 9일
function area = tri_area(b,h)
area = 0.5*b*h;
end
From the command window
A = tri_area(3,2)
댓글 수: 21
Walter Roberson
2022년 12월 26일
When you use the debugger and format long g then what are some sample inputs, and what is the calculated output, and what does the grading program say that the output should be?
추가 답변 (3개)
Siya Desai
2021년 4월 4일
편집: Siya Desai
2021년 4월 4일
function
function [area] = tri_area (b,h)
tri_area = (0.5)*(b)*(h)
code to call your function
tri_area(2,3) %any random input
댓글 수: 1
Walter Roberson
2021년 4월 4일
result = tri_area(2,3) %any random input
function [area] = tri_area (b,h)
tri_area = (0.5)*(b)*(h)
end
Pelden Chodon
2021년 5월 27일
function [area, tri_area] = tri_area(b,h) ;
area = (0.5)*(b)*(h);
v = area(:);
tri_area = sum(v);
end
% Test that your function runs as expected before pressing Submit
[area, tri_area] = tri_area(2,3)
댓글 수: 1
DGM
2023년 2월 4일
You're declaring a variable with the same name as the function you're calling. This will either throw an error or silently cause other errors, depending on where you put the function.
For scalar inputs, summing area serves no purpose. For nonscalar inputs, the results are either wrong, or will throw an error.
% summing a scalar accomplishes nothing
[allareas totalarea] = tri_area(2,3)
% some nonscalar inputs return the wrong results
[allareas totalarea] = tri_area([2 2; 2 2],[3 3; 3 3])
% some nonscalar inputs return the wrong number of wrong results
[allareas totalarea] = tri_area([2 2],[3;3])
% some nonscalar inputs fail completely
[allareas totalarea] = tri_area([2 2],[3 3])
function [allareas, totalarea] = tri_area(b,h)
allareas = (0.5)*(b)*(h); % these parentheses don't do anything
v = allareas(:);
totalarea = sum(v);
end
As this is all largely copy-pasted from other bad answers posted above, I should point out that much of these problems were already openly explained before you posted this. See also: function, array vs matrix operations
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!