Using MATLAB (please use code, not just the output display) Use m functions to d
ID: 2261770 • Letter: U
Question
Using MATLAB (please use code, not just the output display)
Use m functions to do the following math calculations.
(a) Dot product between two vectors are defined by:
Define a function vectordot in MATLAB with the input: vectors a,b, and the output a dot b. The input vectors can be both row or column vectors or one row and the other column vector. Your code should be able to do the following things:
i. Check the input are vectors rather than matrices or high dimension arrays.
ii. Check the lengths of the two input vectors are the same. (hint:length)
iii. Change both input vectors to column vectors.
iv. Calculate the dot product without using loops.
Write ONE m file to test your function with the following test cases:
i. a=1:3, b= (2:4)’
ii. a=1:3, b=2:4
iii. a=1:3, b=1:4
iv.a=ones(4), b=eye(4)
Include the output in your homework.
7 !Explanation / Answer
%%% Matlab function %%%%
function [ c ] = dotproduct(a,b )
c=0;
[m,n]=size(a);
[i,j]=size(b);
if( (m==1 || n==1) && (i==1 || j==1))
l1=length(a);
l2=length(b);
if (l1==l2)
if m==1
a=a';
end
if i==1
b=b';
end
c=sum(a.*b);
fprintf('Dot product of a and b is a.b= %f ',c);
else
disp('Dot product is Not possible beacuse input vector are of different length')
end
else
disp('dot product is only possible for vector');
end
end
%%% test programme
%%%(1)
a=1:3;
b=(2:4)';
c=dotproduct(a,b);
OUTPUT:
Dot product of a and b is a.b= 20.000000
2)
a=1:3;
b=(2:4);
c=dotproduct(a,b);
OUTPUT:
Dot product of a and b is a.b= 20.000000
3)
a=1:3;
b=(1:4);
c=dotproduct(a,b);
OUTPUT:
Dot product is Not possible beacuse input vector are of different length
4)
a=ones(4);
b=eye(4);
c=dotproduct(a,b);
OUTPUT:
dot product is only possible for vector
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.