不同尺寸4D矩阵拼接问题:horzcat调用失败求助
Hey there! Let's break down why your horzcat approach isn't working and get your matrices merged correctly.
The Problem with horzcat
horzcat (short for horizontal concatenation) is designed to merge matrices along the second dimension (columns, dimension 2) by default. Your two matrices:
a1 = zeros(28,28,61,11000)(dimensions: 28×28×61×11000)a2 = zeros(28,28,61,1100)(dimensions: 28×28×61×1100)
Their second dimension is both 28, but you want to combine them along the fourth dimension (the last one, where sizes are 11000 and 1100). Since horzcat tries to stitch along dimension 2 (which already matches), it doesn't do what you need—and throws an error because it's not aligned with your intended operation.
The Correct Solution
To merge along the fourth dimension explicitly, use MATLAB's cat function, which lets you specify exactly which dimension to concatenate along:
% Define your matrices a1 = zeros(28,28,61,11000); a2 = zeros(28,28,61,1100); % Concatenate along the 4th dimension desiredResult = cat(4, a1, a2);
You can verify the result with size(desiredResult)—it should return 28 28 61 12100 (11000 + 1100), which is exactly what you want.
Quick Note
For higher-dimensional matrices (3D and beyond), always use cat(N, ...) where N is the dimension you want to merge along. horzcat and vertcat only work for dimensions 2 and 1 respectively, so they're not suitable for this 4D use case.
内容的提问来源于stack exchange,提问作者Aadnan Farooq A

