Time dependent variable in plot.

2 次查看(过去 30 天)
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.

采纳的回答

Torsten
Torsten 2025-2-5
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 个评论
Steven Lord
Steven Lord 2025-2-5
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))
The expression y(case2) refers to 50 elements in y.
fprintf("But x has %d elements.\n", numel(x))
But x has 151 elements.
y(case2) = 10 + x*0.5; % no x(case2) gives an error
Unable to perform assignment because the left and right sides have a different number of elements.
Brian
Brian 2025-2-6
Both approaches work! Thank you both for answering so quick and clear.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

标签

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by