plotting a function over time using a for loop

5 views (last 30 days)
I've been trying to set a matrix equal to the results of two functions over a range, but am not having any luck. Can someone proofread for me?
x1 = [1:0.01:3];
%set x to a variable from 1 to 3
b1=zeros(1,201);
y1=zeros(1,201);
for x2=1:201;
x3=x1(x2);
b1(x2)=sin(x3)+1;
y1(x2)=x3+exp(-x3/2);
end

Accepted Answer

Image Analyst
Image Analyst on 29 Oct 2014
I improved it some for you and fancied up the graph but I still don't know what you want. Exactly what does "set a matrix equal to the results of two functions over a range" mean ? You have two function and two results from those functions: y1 and b1. Exactly how is the "matrix" supposed to use those two results? Set equal to the sum? The product? The ratio? What???
clear all;
clc;
close all; % Close any prior figure from this program that we have open.
fontSize = 25;
numberOfPoints = 50;
% Set x1 to 50 values from 1 to 3.
x1 = linspace(1, 3, numberOfPoints);
% Preallocate space for other arrays.
b1 = zeros(1, numberOfPoints);
y1 = zeros(1, numberOfPoints);
% Loop, assigning values to y1.
for k = 1 : numberOfPoints;
% Get this x value from x1 array.
this_x = x1(k);
% Calculate b1.
b1(k) = sin(this_x) + 1;
% Calculate y1
y1(k) = this_x + exp(-this_x/2);
end
% Plot y1 as a function of x1.
plot(x1, y1, 'b+-');
hold on;
% Plot b1 as a function of x1.
plot(x1, b1, 'ro-');
grid on;
% Set x and y limits on the axes.
xlim([0, 3]);
ylim([0, 4]);
% Set titles
title('Some functions', 'FontSize', fontSize);
xlabel('x1', 'FontSize', fontSize);
ylabel('y1 and b1', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
  2 Comments
Cameron
Cameron on 29 Oct 2014
Thanks! You gave me what I needed, i just needed to remember how to set up the for loop properly.
Image Analyst
Image Analyst on 29 Oct 2014
You're welcome. Thanks for accepting. You might want to add this to the program:
legend('y1', 'b1');

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!