Reputation: 13
Say I have two functions f(x), g(x), and a vector:
xval=1:0.01:2
For each of these individual x values, I want to define a vector of y-values, covering the y-interval bounded by the two functions (or possibly a matrix where columns are x-values, and rows are y-values).
How would I go about creating a loop that would handle this for me? I have absolutely no idea myself, but I'm sure some of you have something right up your sleeve. I've been sweating over this problem for a few hours by now.
Thanks in advance.
Upvotes: 0
Views: 179
Reputation: 5664
Since you wish to generate a matrix, I assume the number of values between f(x) and g(x) should be the same for every xval
. Let's call that number of values n_pt
. Then, we also know what the dimensions of your result matrix rng
will be.
n_pt = 10;
xval = 1 : 0.01 : 2;
rng = zeros(n_pt, length(xval));
Now, into the loop. Once we know what the y-values returned by f(x) and g(x) are, we can use linspace
to give us n_pt
equally spaced points between them.
for n = 1 : length(xval)
y_f = f(xval(n))
y_g = g(xval(n))
rng(:, n) = linspace(y_f, y_g, n_pt)';
end
This is nice because with linspace
you don't need to worry about whether y_f > y_g
, y_f == y_g
or y_f < y_g
. That's all taken care of already.
For demsonstration, I run this example for xval = 1 : 0.1 : 2
and the two sinusoids f = @(x) sin(2 * x)
and g = @(x) sin(x) * 2
. The points are plotted using plot(xval, rng, '*k');
.
Upvotes: 3