. Write a Matlab script that declares two arrays, each with 4 elements. For all
ID: 3593246 • Letter: #
Question
. Write a Matlab script that declares two arrays, each with 4 elements. For all parts, when printing
an array, each row should be on one line and every line should end in a newline.
a. Set the values in the first array to [-2, 0, 2, 4] by initializing on the line where the array is
declared. Print the array on one line using integer format with fields 3 characters wide
for each element.
b. Set the values in the first array to [-2, 0, 2, 4] by using a counting loop whose loop index
variable goes from 1 to 4 and finding a formula that converts the loop variable into the
needed values. (Spend some time thinking about this, as it may be useful later.) Print
the array using integer format with fields 5 characters wide for each element.
c. Prompt the user for any 4 integer values (they needn't be the ones from parts a and b)
inside of square brackets and read them into the first array directly using input. Do
not declare extra variables to do this. Print the array using an integer format.
d. Use a loop to fill a second array with the values from the first array from part c in
reverse order. Print the second array using an integer format.
Explanation / Answer
**************************************************************
x = [-2, 0, 2, 4];
fprintf('%3d' , x);
fprintf(' ');
for i = 1:4
y(i) = -4 + (2*i);
end
fprintf('%5d' , y);
fprintf(' ');
for j=1:4
x(j) = input("Enter value: ");
end
fprintf('%3d' , x);
fprintf(' ');
for k=1:4
y(5-k) = x(k);
end
fprintf('%3d' , y);
fprintf(' ');
****************************************************************
Sample input:
5
6
7
8
Sample output:
-2 0 2 4
-2 0 2 4
Enter value:
Enter value:
Enter value:
Enter value:
5 6 7 8
8 7 6 5
******************************************************************
Note:
For part a the array is declared in the same line and printed in integer format which is straight forward.
For part b we have devised a formula as:
-4 + (2*i)
when i=1 it evlautes to -2
when i=2 it evlautes to 0
when i=3 it evlautes to 2
when i=4 it evlautes to 4
For part c we take input in array x using the function input()
For part d we store the elements in reverse order in y from the elements of x as:
y(5-k) = x(k)
when k=1 y(4)=x(1)
when k=2 y(3)=x(2)
when k=3 y(2)=x(3)
when k=4 y(1)=x(4)
Thus, the elements are reversed.
I hope this helps.
************************************************************************
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.