1. Write a user-defined MATLAB function for the following math function:

[tex]\[ y(x) = 0.6x^3 e^{-0.47x} + 1.5x^2 e^{-0.6x} \][/tex]

The input to the function is [tex]\( x \)[/tex] and the output is [tex]\( y \)[/tex]. Write the function such that [tex]\( x \)[/tex] can be a vector (use element-by-element operations).

(a) Use the function to calculate [tex]\( y(-2) \)[/tex] and [tex]\( y(4) \)[/tex].
(b) Use the function to make a plot of the function [tex]\( y(x) \)[/tex] for [tex]\( -4 \leq x \leq 8 \)[/tex].



Answer :

Let's begin by writing a user-defined MATLAB function for the given mathematical function. The goal is to ensure that the function can handle both scalars and vectors due to the element-by-element operations required. Here is the step-by-step solution:

### Step 1: Write the MATLAB Function

We will define a MATLAB function named `compute_y` that evaluates the function [tex]\( y(x) = 0.6 x^3 e^{-0.47 x} + 1.5 x^2 e^{-0.6 x} \)[/tex]. Ensure to use element-wise operations when dealing with vectors.

Save the following code in a file named `compute_y.m`:

```matlab
function y = compute_y(x)
% Compute the function y(x) = 0.6x^3exp(-0.47x) + 1.5x^2exp(-0.6x)
y = 0.6 x.^3 . exp(-0.47 x) + 1.5 x.^2 . exp(-0.6 x);
end
```

### Step 2: Calculate [tex]\( y(-2) \)[/tex] and [tex]\( y(4) \)[/tex] using the Function

Create a script, `calculate_values.m`, to use this function and find the values of [tex]\( y(-2) \)[/tex] and [tex]\( y(4) \)[/tex]:

```matlab
% Clear workspace
clear;
clc;

% Define the values for x
x1 = -2;
x2 = 4;

% Calculate y(x1) and y(x2)
y1 = compute_y(x1);
y2 = compute_y(x2);

% Display the results
fprintf('y(-2) = %.4f\n', y1);
fprintf('y(4) = %.4f\n', y2);
```

### Step 3: Plot the Function [tex]\( y(x) \)[/tex] for [tex]\( -4 \leq x \leq 8 \)[/tex]

Extend the script to also plot the function over the specified range:

```matlab
% Clear workspace
clear;
clc;

% Define the range for x
x = linspace(-4, 8, 100);

% Calculate y(x)
y = compute_y(x);

% Plot the function
figure;
plot(x, y, 'b-', 'LineWidth', 2);
xlabel('x');
ylabel('y');
title('Plot of y(x)');
grid on;
```

### Detailed Explanation

1. Function Definition: The `compute_y` function calculates the given mathematical function for any input `x`. By using element-wise operations (`.^` for power and `.*` for multiplication), the function can efficiently handle vectors.

2. Calculation Script: In `calculate_values.m`, we first clear the workspace and define the scalar values `x1 = -2` and `x2 = 4`. Using the `compute_y` function, we calculate and print the corresponding `y` values.

3. Plotting Script: The script then defines a vector `x` ranging from -4 to 8, with 100 evenly spaced points. It calculates the corresponding `y` values and plots them against `x`. The plot includes labeled axes, a title, and a grid for better visualization.

By following these steps, we can calculate and visualize the given mathematical function in MATLAB.