MATLAB中linspace与步长法定义向量的差异及脚本疑问
linspace for Vector Creation in MATLAB Great question! Let's break down the core differences between defining a vector with step-based notation (like your x=-pi:d:pi) and using linspace, using your sine wave plotting script as context.
Key Differences
Element Count & Step Size Calculation
Your step-based approach (x=-pi:d:piwhered=(2*pi)/1000) builds the vector by starting at-pi, addingdeach time, until it reaches or exceedspi. For your specific values, the total span is2pi, so dividing bydgives exactly 1000 steps—meaning this vector will have 1001 elements (since we count both the start and end points).In contrast,
linspace(-pi, pi, 1000)explicitly tells MATLAB to create a vector with exactly 1000 elements, evenly spaced between-piandpi. The step size here is automatically calculated as(pi - (-pi))/(1000-1) = 2pi/999—a tiny bit larger than your originald.Guaranteed End Value
Step notation doesn't always guarantee the final element matches your end value. If the total span (end - start) isn't a perfect multiple of your step size, MATLAB will stop at the largest value that doesn't exceed the end. For example,x=0:0.3:1ends at0.9, not1.linspacealways ensures the last element is exactly your specified end value, no matter how many points you choose. It distributes the points evenly to hit both start and end precisely.Use Case Fit
- Use step notation when you need precise control over the spacing between points (e.g., fixed sampling intervals in signal processing, like your original script's intent to set a specific resolution for sine waves).
- Use
linspacewhen you need exact control over the total number of points (e.g., ensuring a plot uses a fixed number of samples, or when you need to split a range into a specific number of segments).
For Your Script
In your specific example, the visual difference between the two vectors in the plot would be negligible (since both have ~1000 points), but numerically:
x=-pi:d:pihas 1001 points with step2pi/1000linspace(-pi, pi, 1000)has 1000 points with step2pi/999
If you wanted linspace to match the element count of your step-based vector, you'd use linspace(-pi, pi, 1001)—that would give you the exact same vector as x=-pi:d:pi.
内容的提问来源于stack exchange,提问作者jasmin

