Matlab转置0x0数组

时间:2017-08-07 03:38:32

标签: matlab for-loop nested transpose

我需要在不使用transpose(x)的情况下创建自己的数组转置例程。我必须使用嵌套的for循环来交换数组的列和行。我想出了以下代码,但这仅适用于m和n的非零值(列数和行数)。如何调整此代码以使其适用于n = 0和m = 0?提前致谢

clear
clc

% set dimensions
n = 2;
m = 3;

firstArray = rand(n,m);;
for ii = 1:n;
    for jj = 1:m;
       transposedArray(jj, ii) = firstArray(ii, jj); %transposing
    end
end

disp(transposedArray);

1 个答案:

答案 0 :(得分:2)

您需要做的就是在for循环之前检查数组的尺寸,如果它们为零,则返回空矩阵。 更好,只需初始化transposedArray ,如果任何维度为空,则for循环不执行任何操作。

clear
clc

% set dimensions
n = 2;
m = 3;

firstArray = rand(n,m);

transposedArray = [] % Initialize to blank

% Aside: If the arrays are large, pre-allocation can improve performance as below:
% transposedArray = zeros(size(firstArray, 2), size(firstArray, 1))

for ii = 1:n;
    for jj = 1:m;
       transposedArray(jj, ii) = firstArray(ii, jj); %transposing
    end
end

disp(transposedArray);