matlab 1 Find the intersection of the following two lines: y = 3x - 2 y = 5x + 7
ID: 3862307 • Letter: M
Question
matlab
1 Find the intersection of the following two lines:
y = 3x - 2
y = 5x + 7
2 Create row vectors X1 of size 4 with values from 0 to 3 and X2 of size 3 with values from 2 to 4. Now, create a meshgrid using X1 and X1. Read the matlab documentation on meshgrid. Use the following command:
[Y1 Y2] = meshgrid(X1,X2)
What does this give you?
3 Write a function that computes the sum of the elements of a vector using recursion.
4 Write a recursive function that takes in a number and returns the product of the odd numbers between that number and 1.
5 Write a recursive function that takes in a vector and returns the element with the maximum value and the index of that element as two separate return values.
Explanation / Answer
Question 1
y1 =@(x) 3*x-2; %first line
y2 =@(x) 5*x+7; % Second line
% at the point of inter section y1-y2 =0
f = @(x) y1(x)-y2(x);
x = fzero(f,1); % Finsd the value of x at which y1=y2
y = y1(x); % Calculate the y value at x
% print the values
fprintf('The lines intersect at (%0.2f,%0.2f) ',x,y);
OUTPUT
The lines intersect at (-4.50,-15.50)
Question 2)
X1 = 0:3; % Creating a row vector of size 4 from zero to three
X2 = 2:4;% Creating a row vector of size 3 from 2 to 4
[Y1 Y2] = meshgrid(X1,X2)
OUTPUT
Y1 =
0 1 2 3
0 1 2 3
0 1 2 3
Y2 =
2 2 2 2
3 3 3 3
4 4 4 4
Remak: meshgrid command replicates the vectors X1 and X2 to produce the coordinates of a rectangular grid (Y1, Y2). The grid vector X1 is replicated numel(X2) times to form the columns of Y1. The grid vector X2 is replicated numel(X1) times to form the rows of Y2.
Question 3
function S= SumElements(v)
N = length(v); % Computing the lenght of the vector
if(N>1) % if it is grater than 1 then add and call the function again
S = v(N)+SumElements(v(1:N-1));
else % if zise of v is one return the value of the vector
S = v(N);
end
end
OUTPUT
>> v = [1 2 3 4];
>> S= SumElements(v)
S =
10
Question 4)
function P = recursiveProd(n)
if mod(n,2) == 0 % if n is a even number modify n by raducing 1 from n
n = n-1;
end
if n > 1 % if the value of n is grater than 1 perform the product operation and call the function recursively
P = n*recursiveProd(n-2);
else % else return 1
P = 1;
end
end
OUTPUT
>> n = 8;
>> P = recursiveProd(n)
P =
105
Question 5
function [M,I] = recursiveMax(v)
N = length(v); % Compute the length of the vector
if N > 1 % If the size of the vector is more than 1
[M,I] = recursiveMax(v(1:N-1)); % Call the function recursively
if v(N) > M % If M > v(N)
M = v(N); % Update the values of M and I
I = N;
end
else % if length(v) is 1
M = v(1); % give M as v(1) nad I =1
I = 1;
end
end
OUTPUT
>> v = [1 2 5 4 3];
>> [M,I] = recursiveMax(v)
M =
5
I =
3
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.