How to limit function output range?

Say I wan to create a sine wave between -4 to 4, all other values outside -4 and 4 will be zero.j
Here's the code that I thought it was going to work, but I am getting incorrect dimension, is there another way to achieve what I want to achieve?
t = [-10:0.1:10]
t = 1×201
-10.0000 -9.9000 -9.8000 -9.7000 -9.6000 -9.5000 -9.4000 -9.3000 -9.2000 -9.1000 -9.0000 -8.9000 -8.8000 -8.7000 -8.6000 -8.5000 -8.4000 -8.3000 -8.2000 -8.1000 -8.0000 -7.9000 -7.8000 -7.7000 -7.6000 -7.5000 -7.4000 -7.3000 -7.2000 -7.1000
u1 = @(t) t>=4;
u2 = @(t) t<=4;
u3 = @(t) (u1(t) * u2(t));
x1 = @(t) ((10 * sin(pi*t/4)) * u3(t));
plot(t, x1(t));
Error using *
Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix matches the number of rows in the second matrix. To operate on each element of the matrix
individually, use TIMES (.*) for elementwise multiplication.

Error in solution (line 4)
u3 = @(t) (u1(t) * u2(t));

Error in solution (line 5)
x1 = @(t) ((10 * sin(pi*t/4)) * u3(t));
plot(t, x1(-(t+2)/2));

回答(2 个)

I would take a simpler approach:
t = [-10:0.1:10];
x1 =10 * sin(pi*t/4).*(abs(t)<=4);
plot(t,x1)
Use element-wise multiplication.
u1 = @(t) t>=-4;
u2 = @(t) t<=4;
u3 = @(t) (u1(t) .* u2(t));
x1 = @(t) ((10 .* sin(pi*t/4)) .* u3(t));
fplot(x1,[-10,10])

类别

帮助中心File Exchange 中查找有关 Parallel Computing Toolbox 的更多信息

产品

版本

R2022a

标签

提问:

2022-8-27

回答:

2022-8-28

Community Treasure Hunt

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

Start Hunting!

Translated by