Need help about error for Area
8 ビュー (過去 30 日間)
古いコメントを表示
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
0 件のコメント
回答 (3 件)
Image Analyst
2017 年 5 月 5 日
Don't use area as the name of your variable. It's the name of a built in function.
0 件のコメント
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
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
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
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
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 Center および File Exchange で Data Type Conversion についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!