How do use a vector as input to a function?

8 vues (au cours des 30 derniers jours)
Mads Leth Grønbeck
Mads Leth Grønbeck le 9 Sep 2020
Modifié(e) : Steven Lord le 9 Sep 2020
Hello
I got the following assignment as homwork:
Two rectangular boxes are defined by the coordinates of their lower left and upper right corners
The area of the two boxes are given by A
A1 = (x2 − x1)(y2 − y1), and A2 = (x4 − x3)(y4 − y3).
The area of the intersection between the two boxes is given by
Ao = max (0, min(x2, x4) − max(x1, x3) ) · max (0, min(y2, y4) − max(y1, y3))
Create a function named "boxArea" that takes as input the coordinates defining the two boxes as a vector [x1, x2, x3, x4, y1, y2, y3, y4] as well as a string area that specifies what to compute . The function must return the computed area.
For this i have tried to creat the function:
function A = boxArea( [x1,x2,x3,x4,y1,y2,y3,y4],area)
switch area
case 'Box1'
A =(x2-x1)*(y2-y1);
case 'Box2'
A =(x4-x3)*(y4-y3);
case 'Intersection'
A = max(0,min(x2,x4)-max(x1,x3))*max(0,min(y2,y4)-max(y1,y3));
case'Union'
A = 'Box1'+'Box2'-'Intersection';
end
But Matlab just returns the errror:
Error: File: boxArea.m Line: 1 Column: 22
Invalid expression. When calling a function or indexing a variable, use parentheses. Otherwise, check
for mismatched delimiters.
How do i fix this? :)
  1 commentaire
KSSV
KSSV le 9 Sep 2020
You have defined the array [x1,x2,x3,x4,y1,y2,y3,y4]..but MATLAB will nt take it as x1, x2, etc..you need to define them inside the function. Check the given answer.

Connectez-vous pour commenter.

Réponses (1)

KSSV
KSSV le 9 Sep 2020
Modifié(e) : Steven Lord le 9 Sep 2020
function A = boxArea(A,area)
x1 = A(1) ;
x2 = A(2) ;
x3 = A(3) ;
x4 = A(4) ;
y1 = A(5) ;
y2 = A(6) ;
y3 = A(7) ;
y4 = A(8) ;
switch area
case 'Box1'
A =(x2-x1)*(y2-y1);
case 'Box2'
A =(x4-x3)*(y4-y3);
case 'Intersection'
A = max(0,min(x2,x4)-max(x1,x3))*max(0,min(y2,y4)-max(y1,y3));
case'Union'
A = 'Box1'+'Box2'-'Intersection';
end
[SL: Removed an extra end after the definition of y4. With that end in place, the switch was outside the boxArea function and would cause an error.]

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by