Using Matlab Write a function [va, vb, vab] = vectdiv_struct (v, a, b) that take
ID: 3802659 • Letter: U
Question
Using Matlab
Write a function [va, vb, vab] = vectdiv_struct (v, a, b) that takes a vector v of arbitrary length and two numbers a and b as input and that does the following: - aborts if the input v is not a vector OR contains non-integer elements - aborts if the inputs a or b are not scalars OR are not integers - in either case prints an appropriate warning message and does NOT do anything further - in either case the return values should be empty vectors OTHERWISE uses a for loop and conditional structures to: - find the elements of v that are divisible by a and return them in the vector va - find the elements of v that are divisible by b and return them in the vector vb - find the elements of v that are divisible by a AND b and return them in the vector vab Write a function [va, vb, vab] = vectdiv_vect (v, a, b) that uses vectorization and relational/logical operators/functions instead of a loop with conditionals to solve (a). Test BOTH of your functions for the following cases: v = [-1 13 18 -11 -13 49 -47 -39 42 30], a = 2, b = 3 v = [5 8 -7 -3 4], a = 2, b = 3 v = [5 8 -7 -3 4], a = 2.5, b = 3 v = [5 8 -7 -3 4], a = 2, b = [3 5] v = [5 8 -7; 1 -3 4], a = 2, b = 3 v = [5 8 -7 1.5 -3 4], a = 2, b = 3Explanation / Answer
(a)
CODE:
vectdiv_struct.m
function [va, vb, vab] = vectdiv_struct(v,a,b)
% Declare empty vectors.
va = [];
vb = [];
vab = [];
% if the input is not a vector, return
if(~isvector(v))
return
end
% find the size of the input vector
[n,m] = size(v);
% for each item in vector, check if its integer.
for i=1:m
if(rem(v(i),1) ~= 0)
return
end
end
% check if a is scalar and integer
if(~isscalar(a) || (rem(a,1)~=0))
return
end
% check if b is scalar and integer
if(~isscalar(b) || (rem(b,1)~=0))
return
end
% find values in vector divisible by a and
% load it in va.
j = 1;
for i=1:m
if(rem(v(i),a) == 0)
va(j) = v(i);
j = j + 1;
end
end
% find values in vector divisible by b and
% load it in vb.
j=1;
for i=1:m
if(rem(v(i),b) == 0)
vb(j) = v(i);
j = j + 1;
end
end
% find values in vector divisible by a and divisible by b
% and load it in vab.
j = 1;
for i=1:m
if((rem(v(i),a) == 0) && (rem(v(i),b) == 0))
vab(j) = v(i);
j = j + 1;
end
end
end
OUTPUT:
>> v = [-1 13 18 -11 -13 49 -47 -39 42 30]
v =
-1 13 18 -11 -13 49 -47 -39 42 30
>> a = 2
a =
2
>> b = 3
b =
3
>> [v1,a1,b1] = vectdiv_struct(v,a,b)
v1 =
18 42 30
a1 =
18 -39 42 30
b1 =
18 42 30
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.