plot a function that has a variable that changes with time

30 次查看(过去 30 天)
The function has a variable ap that changes at t >= 100s. How do I plot that?
close all; clear; clc
tspan = [0 150];
x0 = [1];
t = linspace(0,150);
bp = 2; am = -1; bm = 1; r = 0.5; gamma = 2;
theta2 = func(t,am,bp)
plot(t,theta2)
function theta2 = func(t,am,bp)
if t >= 100
ap = 2;
else
ap = 1;
end
theta2 = (am-ap)/bp;
end

回答(1 个)

Chien-Han Su
Chien-Han Su 2021-3-28
编辑:Chien-Han Su 2021-3-28
In your block of 'func', watch out that the 1st input argument 't' might be and indeed a vector in your case through
t = linspace(0,150);
This leads to an ambiguous result , in the 'func', for the if condition
if t >= 100
By typing in the command window
linspace(0,150) >= 100
you can see explicitly that the result is a vector not a single boolean value.
Hence, I suggest you modify the 'func' block by explicitly assign the size of output 'theta2' according to the input 't' and compute elements of the result using a loop. Namely, revise the code into
close all; clear; clc
tspan = [0 150];
x0 = [1];
t = linspace(0,150);
bp = 2; am = -1; bm = 1; r = 0.5; gamma = 2;
theta2 = func(t,am,bp);
plot(t,theta2,'LineWidth',1)
axis([-inf inf -2 -0.5]);
function theta2 = func(t,am,bp)
numInput = numel(t);
theta2 = zeros(size(t));
for i = 1:numInput
if t(i) >= 100
ap = 2;
else
ap = 1;
end
theta2(i) = (am-ap)/bp;
end
end
The result is shown as follows
Edit: fix typos

类别

Help CenterFile Exchange 中查找有关 Time Series Events 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by