Need help about error for Area

조회 수: 8 (최근 30일)
RG
RG 2017년 5월 4일
댓글: dpb 2017년 5월 5일
Need to calculate area of triangle getting error with nargchk need help to fix it.
function area = area2d(x1,y1,x2,y2,x3,y3) %function definition
msg = nargchk(1,6,nargchk);%total 6 inputs
error(msg);%error message
area=0.5*(x1(y2-y3)-x2*(y1-y3)+x3*(y1-y2)); % area calculation from the given formula

답변 (3개)

Image Analyst
Image Analyst 2017년 5월 5일
Don't use area as the name of your variable. It's the name of a built in function.

dpb
dpb 2017년 5월 4일
편집: dpb 2017년 5월 4일
You've got nargchk in the argument list as first problem...
function area = area2d(x1,y1,x2,y2,x3,y3)
error(nargchk(6,6,nargin))
...
Your function as written requires 6 and only 6 arguments, not a variable number from 1 to 6...
ADDENDUM It would be "more Matlab-y" to use x- and y- arrays instead of six individual elements in which case the number of arguments would be two and you'd then check for 3 elements in each. But, this refactoring could make the upper level code much more succinct.
  댓글 수: 3
dpb
dpb 2017년 5월 4일
msg = error(nargchk(6,6,nargin));
Lose the assignment; error eats the message if it isn't null and throws the error...you're done at that point.
The line I coded was
error(nargchk(6,6,nargin))
altho I see I left off a closing parens; will fix that in Answer.
That's the only error-checking line you need (or want; there's no point is saving the message for anything).
dpb
dpb 2017년 5월 4일
On the warning regarding obsolescence, better practice given that would be to just write
narginchk(6,6)
and be done; it'll call error internally if needed.

댓글을 달려면 로그인하십시오.


Steven Lord
Steven Lord 2017년 5월 5일
In addition to the narg* usage dpb mentioned, look at the first part of your last line.
area=0.5*(x1(y2-y3) ...
You don't want to try to compute element number (y2-y3) of the variable x1. You want to multiply (y2-y3) by x1.
area=0.5*(x1*(y2-y3) ...
  댓글 수: 1
dpb
dpb 2017년 5월 5일
Good catch, Steven, I didn't look at rest of code much (like at all).
In line with previous note on input as arrays instead of a bunch of named variables, OP may want to consider
doc polyarea
--Matlab has the functionality already supplied.
On IA's note re: use of area, it won't hurt here as it's the internal name of the return variable that goes away once the function executes so won't alias the plotting area function, but is an important point in general. If assigns the result of the function in the calling context, it would.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by