问题
I am new to MATLAB and currently working on my homework assignment. I am trying to declare the x
variable as the following:
Create a linearly spaced array
x
of size (1 × 200) comprising values ranging from–pi
topi
.
I've tried this code:
x=[-pi:200:pi];
but I'm not sure if it's the correct way to do this or not.
回答1:
You can use linspace
as follow:
x = linspace(-pi, pi, 200);
check this out for an example: https://www.mathworks.com/help/matlab/ref/linspace.html
回答2:
The other answer shows how to use linspace
, this is the correct method.
But you can also use the colon operator and some simple arithmetic to do this:
x = -pi : 2*pi/199 : pi
-- This means: go from -π to π in steps of such a size that we get exactly 200 values.x = (0:199) * (2*pi/199) - pi
-- This means: create an array with 200 integer values, then scale them to the right range.
Note that you shouldn't use square brackets []
here. They are for concatenating arrays. The colon operator creates a single array, there is nothing to concatenate it with.
来源:https://stackoverflow.com/questions/54284753/creating-a-linearly-spaced-array-of-a-particular-size