How do use a vector as input to a function?

조회 수: 4 (최근 30일)
Mads Leth Grønbeck
Mads Leth Grønbeck 2020년 9월 9일
편집: Steven Lord 2020년 9월 9일
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
KSSV
KSSV 2020년 9월 9일
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.

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

답변 (1개)

KSSV
KSSV 2020년 9월 9일
편집: Steven Lord 2020년 9월 9일
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.]

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by