MATLAB Answers

Issues defining dot product function

20 views (last 30 days)
Amanda
Amanda on 22 Jan 2020
Answered: Walter Roberson on 22 Jan 2020
I'm working on my very first MATLAB assignment with no previous experience and I have to create a function called 'dotcheck', which checks whether the dot product of two column vectors can be found, and then it calculates the dot product.
I'm pretty sure I have the first part of my code correct, but I keep running into an error that says "Unrecognized function or variable 'dot'." when I try to run (for example):
u=randi(10,5,1), v=randi(10,5,1)
[d1,d2]=dotcheck(u,v);
in my Live Editor with my dotcheck function:
function [d1,d2] = dotcheck(u,v)
format compact
m=length(u);
n=length(v);
if isequal(m,n)
fprintf('both vectors have %i entries\n',n)
else
disp('the dot product is not defined')
d1=[];
d2=[];
return
end
d1=transpose(u)*v;
d2=0;
for i=1:n
d2=d2+u(i)*v(i);
end
d=dot(u,v);
if d1==dot(u,v), d2==dot(u,v)
fprintf('the code is correct\n')
else
disp('check the code!')
return;
end
if d>0
disp('the angle between the vectors is either acute or zero')
dot(u,v)=norm(u)*norm(v)
dot(u,v)/(norm(u)*norm(v))-1==0
end
if d<0
disp('the angle between the vectors is obtuse or 180 degrees')
dot(u,v)=norm(u)*norm(v)*cos(180)
dot(u,v)/(norm(u)*norm(v))+1==0
end
if d==0
disp('the angle between the vectors is 90 degrees')
dot(u,v)=norm(u)*norm(v)*cos(90)
end
end
For some reason, it has an issue with the line:
d=dot(u,v);
because it doesn't understand that I'm trying to define the variable d to be the operation dot(u,v).
I tried using "dotprod" and other functions to test it out, and it had no problems with those. I can also use the operation dot(u,v) for some u and v in the Live Editor, so I know the function is defined.
I'm not sure if my coding afterwards is correct or not (because it won't let me get past this error), so I would also appreciate thoughts on how I can fix that to display the correct dot products for each particular condition.
Any advice or help is appreciated.
Thank you so much!

  1 Comment

Sindar
Sindar on 22 Jan 2020
dot is a built-in function, so it should be recognized (and you shouldn't redefine it in your code with dot(u,v)=)

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 22 Jan 2020
In newer versions of MATLAB, if you use a name as both a function and a variable, then it will treat it as always being a variable and will fail at the point where you try to use it as a function. You are using dot as both a function and a variable, so you are running into problems.
Note by the way that in
dot(u,v)=norm(u)*norm(v)
you would encounter problems because your u and v are not expected to be positive integers suitable for use as subscripts.
See also my discussion of formula versus indexing at

  0 Comments

Sign in to comment.

Sign in to answer this question.


Translated by