Matlab中Stem函数使用:如何调整离散卷积绘图范围至n=0到25?
Hey there! Let's sort this out for you. First off, it's totally normal that your convolution result y has length 51 — when you convolve two sequences each of length 26, the output length is always len(a) + len(b) - 1 (so 26+26-1=51 here). That's just how discrete convolution works!
To plot only the values corresponding to n=0 to n=25, you just need to slice the first 26 elements of your full convolution result. Here's how to do this in two common tools:
Python (with NumPy & Matplotlib)
import numpy as np import matplotlib.pyplot as plt # Example input sequences (length 26, indices 0-25) x = np.random.randn(26) h = np.random.randn(26) # Compute full convolution (gives 51-point result; this is NumPy's default mode) y_full = np.convolve(x, h) # Extract the first 26 elements (matches n=0 to 25) y_selected = y_full[:26] # Your original n array (0 to 25) n = np.arange(26) # Plot the result plt.stem(n, y_selected, use_line_collection=True) plt.xlabel('n') plt.ylabel('y[n]') plt.title('Convolution Result for n=0 to 25') plt.grid(True) plt.show()
Quick Notes:
- We use the default
mode='full'to get the complete convolution output — no need to specify it explicitly unless you've changed it before. - Slicing
y_full[:26]grabs exactly the elements that line up with yourn=0ton=25range.
MATLAB
% Example input sequences (length 26) x = randn(26, 1); h = randn(26, 1); % Compute full convolution (51-point result) y_full = conv(x, h, 'full'); % Extract first 26 elements (MATLAB uses 1-based indexing, so 1:26 maps to n=0:25) y_selected = y_full(1:26); % Plot stem(0:25, y_selected); xlabel('n'); ylabel('y[n]'); title('Convolution Result for n=0 to 25'); grid on;
Important Heads-Up:
Skip using mode='same' (or 'same' in MATLAB) here! While it gives a 26-point result, it's centered on the full convolution — not the first 26 values you need for n=0 to n=25. Sticking with the full convolution and slicing is the right call for your specific request.
内容的提问来源于stack exchange,提问作者Vinícius Lopes Simões

