如何用不同维度行向量创建矩阵?MATLAB维度不匹配问题求解
Got it, let's fix this concatenation error you're running into. The vertcat function throws that error because it requires every row vector you're combining to have the exact same length—right now your b1 and b2 are 1×25, while a3, b3, a4, and b4 are only 1×9. Padding the shorter vectors with NaN values to match the longest vector's length is the perfect solution, and here's how to implement it cleanly:
Step-by-Step Solution
- Collect all vectors into a cell array: This makes batch processing easy, even if you add more vectors later.
- Find the longest vector's length: Use this as the target length for all padded vectors.
- Pad short vectors with NaNs: Extend each shorter vector to match the target length by appending
NaNs. - Concatenate padded vectors: Now all rows have the same length, so
vertcatworks without errors.
Full Working Code
Replace your original A=[b1;b2;a3;b3;a4;b4] line with this complete integrated script:
clear b1 = fir1(24,[0.5 0.9]); f=[0 0.6 0.6 0.8 0.8 1]; m=[0 0 1 1 0 0]; b2=fir2(24,f,m); [b3,a3] = butter(4,[0.6 0.8]); [b8,a8] = butter(4,[2*pi*900 2*pi*1200],'s'); [b4,a4] = impinvar(b8,a8,3000); % Gather all vectors into a cell array for easy processing all_vectors = {b1, b2, a3, b3, a4, b4}; % Calculate the length of the longest vector max_vec_length = max(cellfun(@length, all_vectors)); % Pad each vector with NaNs to match the longest length padded_vectors = cellfun(... @(vec) [vec, NaN(1, max_vec_length - length(vec))], ... all_vectors, ... 'UniformOutput', false ... ); % Concatenate into a single matrix A = vertcat(padded_vectors{:});
How This Works
cellfun(@length, all_vectors): Iterates over every vector in the cell array to get its length, thenmax()grabs the largest value (25 in your case).- The anonymous function
@(vec) [vec, NaN(1, max_vec_length - length(vec))]takes each short vector and appends just enoughNaNs to make its length equal to the longest vector. vertcat(padded_vectors{:}): Expands the cell array of padded vectors and concatenates them vertically into a valid matrix.
This approach is flexible too—if you add more vectors later (of any length), the code will automatically adjust to pad everything to the new longest vector's length.
内容的提问来源于stack exchange,提问作者Scavenger23

