是否有人知道如何在不使用内置命令的情况下将行向量[6 8 2]
转换为列向量。我想在没有for循环的情况下这样做。请给我一个想法。有人问我这是家庭作业,我说不,这是我工作的一部分。我正在尝试使用hdl编码器将MATLAB代码转换为vhdl,但hdl编码器似乎不支持转置函数。
答案 0 :(得分:10)
一些选项:
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)
答案 1 :(得分:4)
您可以使用(:)
技巧
t = [1 2 3];
t(:)
ans =
1
2
3
UPDATE :您应该仅在以下情况下使用此方法:您有一个向量(不是矩阵)并且想要确保它是一个列向量。当您不知道变量具有什么类型(列,行)时,此方法很有用。
检查出来
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