Question 2 (a) Write the result of executing the following commands in MATLAB: X
ID: 3909222 • Letter: Q
Question
Question 2
(a) Write the result of executing the following commands in MATLAB:
X = [1 [[5] [9, -1]] [3]]
Y = [1:3; 4 4 4]
Z = [4:6; 8:10; 15:19]
[3 marks]
(b) Given the vector Q = [5, 0, 12, 3], write the output after executing
each
of
the following commands:
Q = [Q, 9]
Q(2) = []
Q(end-1) = sum(Q)
[3 marks]
(c) Given a matrix, M:
1 5 9
7 8 7
3 6 2
Write the values in the matrix after
each
of the following commands:
M(1,:) = 7
M([3, 1], [2, 3]) = 0
[3 marks]
(d) Write equivalent code to the one shown below by replacing the
while loop
with a
for loop
.
a = [];
x = 5;
while x <= 15
a[x-4] = x^2;
x = x + 1;
end
[4 marks]
(e) Write the small program from the previous question using a single line of
code with vector operations.
[2 marks]
(f) Write a MATLAB script that uses a loop to
the contents of two vectors
interleaved in to one vector. Assume both vectors are the same length. For
example, if A contains [1, 7, 6, 9], and B contains [4, 4, 2, 5], such that
executing the script should display the following:
>> zip_script
1 4 7 4 6 2 9 5
>>
Hint: Avoid assigning the result in to a vector before printing them.
Explanation / Answer
(a) Write the result of executing the following commands in MATLAB:
X = [1 [[5] [9, -1]] [3]]
Output
X =
1 5 9 -1 3
Y = [1:3; 4 4 4]
Output
Y =
1 2 3
4 4 4
Z = [4:6; 8:10; 15:19]
Output
Error: Dimensions of matrices being concatenated are not consistent.
----------------------------------------------------------------------------------------------------------------------------------------------------
(b) Given the vector Q = [5, 0, 12, 3], write the output after executing each of the following commands:
Q = [Q, 9]
Output
Q =
5 0 12 3 9
Q(2) = []
Output
Q =
5 12 3 9
Q(end-1) = sum(Q)
Output
Q =
5 12 29 9
-----------------------------------------------------------------------------------------------------------------------------------------------------
(c) Given a matrix, M:
1 5 9
7 8 7
3 6 2
Write the values in the matrix after each of the following commands:
M(1,:) = 7
Output
M =
7 7 7
7 8 7
3 6 2
M([3, 1], [2, 3]) = 0
Output
M =
7 0 0
7 8 7
3 0 0
-----------------------------------------------------------------------------------------------------------------------------------------------------
(d) Write equivalent code to the one shown below by replacing the while loop with a for loop
a = [];
x = 5;
while x <= 15
a[x-4] = x^2;
x = x + 1;
end
Ans:
a = [];
for x=5:15
a(x-4) = x^2;
end
------------------------------------------------------------------------------------------------------------------------------------------------------
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.