0

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.

1 Answer 1

3

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');. Example

Sign up to request clarification or add additional context in comments.

1 Comment

That is absolutely brilliant, that is exactly what I was looking for. It is very much appreciated, I don't think I'd ever figure that out myself. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.