150k views
4 votes
Problem #3

In MatLab code
1. Define an array x(6,6) and fill it with integer random numbers in the interval 0 to
5. Print the array
2. Define an array y(6,6) and fill it with integer random numbers in the interval of -5
to 15. Print the array
3. Define an array z(6,6) and fill it with:
z=5x3 −8xy

D5 = 6

D8 = 4
All array operations are element by element. Print the array
4. Use the switch construct to perform the following options:
a. Find the sum of the element in both diagonal of z. Use "fprintf" to print the
result.
b. How many elements in z have the value -1 "fprintf" the result.
c. How many elements of z has a value greater than 12, "fprintf" the result.
d. What is the sum of numbers in the 2 by 2 inner array. Print the results.

1 Answer

3 votes

Answer:

Here's the MatLab code to complete the tasks:

```

% 1. Define an array x(6,6) and fill it with integer random numbers in the interval 0 to 5. Print the array

x = randi([0,5],6,6);

disp(x);

% 2. Define an array y(6,6) and fill it with integer random numbers in the interval of -5 to 15. Print the array

y = randi([-5,15],6,6);

disp(y);

% 3. Define an array z(6,6) and fill it with: z=5x3 −8xy

z = 5*x.^3 - 8*x.*y;

disp(z);

% 4. Use the switch construct to perform the following options:

% a. Find the sum of the element in both diagonal of z. Use "fprintf" to print the result.

sum_diag = sum(diag(z)) + sum(diag(fliplr(z)));

fprintf('The sum of the elements in both diagonals of z is %d.\\', sum_diag);

% b. How many elements in z have the value -1 "fprintf" the result.

num_neg_one = sum(z(:) == -1);

fprintf('There are %d elements in z that have the value -1.\\', num_neg_one);

% c. How many elements of z has a value greater than 12, "fprintf" the result.

num_greater_twelve = sum(z(:) > 12);

fprintf('There are %d elements in z that have a value greater than 12.\\', num_greater_twelve);

% d. What is the sum of numbers in the 2 by 2 inner array. Print the results.

inner_array = z(2:3,2:3);

sum_inner_array = sum(inner_array(:));

fprintf('The sum of the numbers in the 2 by 2 inner array is %d.\\', sum_inner_array);

```

This code defines arrays `x`, `y`, and `z` as instructed, then performs the four tasks using a switch statement. Task a is accomplished by using the `diag` function to extract the two diagonals of `z`, summing them, and printing the result with `fprintf`. Task b is accomplished by using logical indexing to find all elements of `z` that are equal to -1, summing them, and printing the result. Task