不使用内置 MATLAB 命令转置向量

Transpose of a vector without builtin MATLAB command

有谁知道如何在不使用内置命令的情况下将行向量 [6 8 2] 转换为列向量。我想在没有 loop.A 想法的情况下这样做。有人问我这是家庭作业吗?我说不是,这是我工作的一部分。我正在尝试使用 hdl 编码器将 MATLAB 代码转换为 vhdl,但 hdl 编码器似乎不支持转置函数。

部分选项:

R = 1:10; %// A row vector

%// using built-in transpose
C = R';   %'// be warned this finds the complex conjugate
C = R.';  %'// Just swaps the rows and columns
C = transpose(R);    

%// Flattening with the colon operator
C = R(:); %// usually the best option as it also convert columns to columns...

%// Using reshape
C = reshape(R,[],1);

%// Using permute
C = permute(R, [2,1]);

%// Via pre-allocation
C = zeros(numel(R),1);
C(1:end) = R(1:end);

%// Or explicitly using a for loop (note that you really should pre-allocate using zeros for this method as well
C = zeros(numel(R),1); %// technically optional but has a major performance impact
for k = 1:numel(R)
    C(k,1) = R(k);  %// If you preallocated then C(k)=R(k) will work too
end

%// A silly matrix multiplication method
C = diag(ones(numel(R),1)*R)

您可以使用(:) 技巧

t = [1 2 3];
t(:)
ans =

 1
 2
 3

UPDATE:你应该只在以下情况下使用这个方法:你有一个向量(不是矩阵)并且想确保它是一个 column-vector。当您不知道变量的向量类型(列、行)时,此方法很有用。

看看这个

t = [1 2 3]'; %// column vector
t(:)
ans =

 1
 2
 3

但是

A=magic(3); 
A(:)
ans =
 8
 3
 4
 1
 5
 9
 6
 7
 2