Need help about error for Area
9 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposte (3)
Image Analyst
il 5 Mag 2017
Don't use area as the name of your variable. It's the name of a built in function.
0 Commenti
dpb
il 4 Mag 2017
Modificato: dpb
il 4 Mag 2017
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 Commenti
dpb
il 4 Mag 2017
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
il 4 Mag 2017
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
il 5 Mag 2017
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 Commento
dpb
il 5 Mag 2017
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.
Vedere anche
Categorie
Scopri di più su Data Type Conversion in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!