create a loop to compute 20 values of a function and plot the results in matlab

You can use a for loop to compute 20 values of a function and plot the results in Matlab. Here's an example code:

main.m
% Define the function
f = @(x) x.^2 + 2.*x + 1;

% Define the range of x values
x = linspace(-5, 5, 20);

% Compute the y values for each x value using a for loop
y = zeros(size(x));
for i = 1:length(x)
    y(i) = f(x(i));
end

% Plot the results
plot(x, y)
xlabel('x')
ylabel('y')
title('Function plot')
305 chars
18 lines

In this example, we define a function f(x) = x^2 + 2x + 1 using an anonymous function. We then define a range of x values using the linspace function, which generates 20 evenly spaced values between -5 and 5.

We use a for loop to compute the corresponding y values for each x value and store them in an array y. Finally, we plot the results using the plot function and add labels and a title to the plot using the xlabel, ylabel, and title functions.

gistlibby LogSnag