Error using cross and not calculating correctly

I am trying to write the code to calculate the area of a trianlge given three vectors. I keep getting an answer that is wrong. Here's the code that I wrote:
input a=['Enter vector a:'];
input b=['Enter vector b:'];
input c=['Enter vector c:'];
A=norm(cross('c-a','b-a'));
Area=A/2
This is what I get when I plug in the following vectors:
>> TAREA
a=['Enter vector a:'][1 2 2]
b=['Enter vector b:'][3 1 4]
c=['Enter vector c:'][5 2 1]
Area =
53.4649
The area should be 5.4083. Why is the code not working properly?

답변 (2개)

CA = 'c-a'
CA = 'c-a'
BA = 'b-a'
BA = 'b-a'
dCA = double(CA)
dCA = 1×3
99 45 97
dBA = double(BA)
dBA = 1×3
98 45 97
cross(CA,BA)
ans = 1×3
0 -97 45
cross(dCA,dBA)
ans = 1×3
0 -97 45
From this you can see that cross('c-a','b-a') is the same as cross([99 45 97],[98 45 97]) . You are taking the cross-product of the characters ['c' '-' 'a'] and ['b' '-' 'a'] rather than the cross-product of the difference in values of variables c and a and b.

댓글 수: 3

Braden
Braden 2023년 3월 14일
Rewrote the code to this:
a='Enter vector a';
b='Enter vector b';
c='Enter vector c';
Area=norm(cross(c-a,b-a))/2
Get this error message now:
>> TAREA
A and B must be of length 3 in the dimension in which the cross product is taken.
Error in TAREA (line 4)
Area=norm(cross(c-a,b-a))/2
a='Enter vector a';
double(a)
ans = 1×14
69 110 116 101 114 32 118 101 99 116 111 114 32 97
You just created a as the vector ['E', 'n', 't', 'e', 'r', ' ', 'v', 'e', 'c', 't', 'o', 'r', ' ', 'a']
Try
a = input('Enter vector a ');
b = input('Enter vector b ');
c = input('Enter vector c ');
Braden
Braden 2023년 3월 14일
Got it now. Thanks

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

Dyuman Joshi
Dyuman Joshi 2023년 3월 14일
편집: Dyuman Joshi 2023년 3월 14일
You are using character scalars instead of using variables. The result you get are corresponding to the ascii values of the characters
a=[1 2 2];
b=[3 1 4];
c=[5 2 1];
%Using variables
Area1=norm(cross(c-a,b-a))/2
Area = 5.4083
Area2=norm(cross('c-a','b-a'))/2
A = 53.4649

댓글 수: 3

Braden
Braden 2023년 3월 14일
Rewrote the code to this:
a='Enter vector a';
b='Enter vector b';
c='Enter vector c';
Area=norm(cross(c-a,b-a))/2
Get this error message now:
>> TAREA
A and B must be of length 3 in the dimension in which the cross product is taken.
Error in TAREA (line 4)
Area=norm(cross(c-a,b-a))/2
If you want to ask a user for inputs, try this -
a=input('Enter vector a\n');
b=input('Enter vector b\n');
c=input('Enter vector c\n');
Area1=norm(cross(c-a,b-a))/2
When you run the above code, a prompt will ask to input the values for a, b and c. Provide the values of vectors respectively and you will get the value of Area
Braden
Braden 2023년 3월 14일
Got it now. Thanks

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

카테고리

태그

질문:

2023년 3월 14일

댓글:

2023년 3월 14일

Community Treasure Hunt

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

Start Hunting!

Translated by