Time dependent variable in plot.
4 views (last 30 days)
Show older comments
Hello,
Fairly new to Matlab, so probably a simple question/answer.
I want to make a plot where my y-axis value depends on the timezone (x-axis). For example:
When x >= 0 & x < 5
y = 10;
When x >= 5 & x < 10
y = 10 + x*0.5;
when x >= 10 & < 15
y = -5;
The values above are just for the example.
What is the best (most efficient) way to make a plot that shows this?
Thanks in advance.
0 Comments
Accepted Answer
Torsten
on 5 Feb 2025
The simplest method is to define x, compute y in a loop and plot:
x = 0:0.1:15;
for i = 1:numel(x)
if x(i) >= 0 & x(i) < 5
y(i) = 10;
elseif x(i) >= 5 & x(i) < 10
y(i) = 10 + x(i)*0.5;
elseif x(i) >= 10 & x(i)<= 15
y(i) = -5;
end
end
plot(x,y)
2 Comments
Steven Lord
on 5 Feb 2025
Another approach is to use logical indexing to create "masks" for each section of the x and y vectors that fall into each of your regions and use the appropriate section of the x vector to populate the corresponding section of the y vector. We'll start off with your x data.
x = 0:0.1:15;
We can create a y vector the same size as x with some "default" data. I'll use the zeros function but you could use the ones, inf, nan, or any of a number of functions.
y = zeros(size(x));
Now let's select the appropriate elements of x for your first region.
% When x >= 0 & x < 5
case1 = (x >= 0) & (x < 5);
Use case1 to select which elements in y are to be set to 10.
% y = 10;
y(case1) = 10;
We can do the same thing for case 2:
% When x >= 5 & x < 10
case2 = (x >= 5) & (x < 10);
But this time we're not setting elements of y to a constant, we're setting them to a function of the corresponding elements in x. So in this case we need to index using case2 both in the assignment to y and in the referencing from x. [People often miss the indexing into x on the right side of the equals sign, in which case they'd get an error that the things on the two sides of the equals sign are not the same size. (*)]
% y = 10 + x*0.5;
y(case2) = 10 + x(case2)*0.5;
And the same for the third case. But I'll let you finish that.
% when x >= 10 & < 15
% y = -5;
Now if we call plot with x and y, the first two parts ought to match Torsten's plot. The third part won't (note the limits on the Y axis) since I left that as an exercise to the reader :)
plot(x, y)
(*) See?
fprintf("The expression y(case2) refers to %d elements in y.\n", nnz(case2))
fprintf("But x has %d elements.\n", numel(x))
y(case2) = 10 + x*0.5; % no x(case2) gives an error
More Answers (0)
See Also
Categories
Find more on Annotations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!