使用reshape 时,输入元素的数量必须等于输出(重构)元素的数量。
在您的情况下:length(a) 必须等于 num_of_rows_calc*num_cols_wanted。
执行b = zeros(...) 然后b = reshape(...) 只会覆盖b 的值(用零填充b 没有帮助)。
-
您可以用零填充b(创建一个“长”向量),并将a 元素复制到a 的开头:
b = zeros(num_of_rows_calc*num_cols_wanted, 1);
b(1:length(a)) = a;
-
在b的元素数量正确后,我们可以重塑b:
b = reshape(b, [num_cols_wanted, num_of_rows_calc])';
注意:
在 OCTAVE 中重塑向量首先按列(从上到下)对元素进行排序。
对于按行排序,我们可以重塑为 cols x 行并转置结果。
完整的代码示例:
%a=[1:32734]';
a = (1:10)';
num_cols_wanted=3; %640;
num_of_rows_calc=ceil(size(a,1)/num_cols_wanted); %use ceil to get whole number rounded up
num_cells_to_add=mod(size(a,1),num_cols_wanted); %extra cells needed to even array out
b = zeros(num_of_rows_calc*num_cols_wanted, 1); %Create a vector of zeros with desired number of elements.
b(1:length(a)) = a; %Copy a into the b - keeping the zeros at the end of b (we could also add zero padding at the end of a).
%Reshape to num_cols_wanted x num_of_rows_calc and transpose, because OCTAVE ordering is "column major".
b = reshape(b, [num_cols_wanted, num_of_rows_calc])'; %reshape b array into preallocated b array
结果:
b =
1 2 3
4 5 6
7 8 9
10 0 0
3D 输出示例:
a = cat(3, (1:10)', (21:30)', (31:40)');
a = squeeze(a); % Remove redunded dimentsion
num_cols_wanted=4;%640;
num_of_rows_calc=ceil(size(a,1)/num_cols_wanted); %use ceil to get whole number rounded up
num_cells_to_add=mod(size(a,1),num_cols_wanted); %extra cells needed to even array out
b = zeros(num_of_rows_calc*num_cols_wanted, 3); %Create 3 columns matrix of zeros with desired number of elements.
b(1:length(a), :) = a; %Copy a into the b - keeping the zeros at the end of b (we could also add zero padding at the end of a).
%Reshape to 3 x num_cols_wanted x num_of_rows_calc and permute, because OCTAVE ordering is "column major".
b = reshape(b, [num_cols_wanted, num_of_rows_calc, 3]); %reshape b array into preallocated b array
b = permute(b, [2, 1, 3]);