You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用不同维度行向量创建矩阵?MATLAB维度不匹配问题求解

How to Combine Mismatched-Length Row Vectors into a Matrix in MATLAB (Padding with NaNs)

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 vertcat works 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, then max() 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 enough NaNs 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:38:08