how to Use a for loop to evaluate the composite function at each value of x
5 views (last 30 days)
Show older comments
I am given two functions and are required to evaluate the values of x given for composite function.
2 Comments
John D'Errico
on 29 Mar 2024
Ok. So you know what to do. Use a for loop. Do you know what a for loop is? If not, then have you spent any time with the basic tutorials? If not, then why not?
As far as evaluating a composite function. Evaluate the inside function. Get a result. Then evaluate the outside function. Where is the problem?
If a problem seems too large to handle, then break it down into small pieces. Learn how to deal with each piece separately. Then put it all together. Here, that means learning what a for loop is. TRY IT! Make an effort.
Answers (1)
Rupesh
on 16 Apr 2024
Hi Lindelwa,
I understand that you're looking to evaluate composite functions in MATLAB for a series of input values. Composite functions involve applying one function to the results of another, such as ”(g(f(x)))”. To achieve this, especially for multiple values of (x), you can use MATLAB's capabilities for anonymous functions along with loops or vectorized operations for efficiency. Below are some example methods that will give you a clear understanding of composite functions.
%Let's define (f(x) = x^2) and (g(x) = sin(x)), where you want to compute (g(f(x))) for a range of (x) values.
% Define the functions
f = @(x) x.^2; % Function f(x) = x^2
g = @(x) sin(x); % Function g(x) = sin(x)
Using a For Loop
Iterates over each element in “x_values”, applying (f) first, then (g), and storing the result.
x_values = 1:5;
results = zeros(size(x_values));
for i = 1:length(x_values)
results(i) = g(f(x_values(i)));
end
disp('Results using a for loop:');
disp(results);
Using Vectorized Operations
MATLAB is optimized for vector operations, which can be more efficient than using loops. This method is preferable when your functions support vectorized inputs.
x_values = 1:5; % Define a range of x values
results = g(f(x_values)); % Directly compute g(f(x)) in a vectorized manner
disp('Results using vectorized operations:');
disp(results);
Depending on your preference or the complexity of the functions, you can choose either the loop or the vectorized approach to evaluate composite functions for multiple inputs in MATLAB. Both methods are valid, but vectorized operations are typically more efficient and are encouraged when applicable. You can also refer to the below documents regarding the operations of the functional composition.
Hope this helps!
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!