如果我向行向量 x 添加一个 newvlaue,它将是
x = [newvlue, x] % use of ,
Run Code Online (Sandbox Code Playgroud)
但如果到列向量 x,它将是
x = [newvlue; x] % use of ;
Run Code Online (Sandbox Code Playgroud)
所以我必须提前知道它是行向量还是列向量才能执行此前端插入。但我可能并不总是知道 x 是用户输入。所以每次我需要事先执行这个行向量或列向量检查。但是,假设我真的不想关心它是行向量还是列向量,我只需要在数组的前面添加一个元素。有没有什么优雅的方式来编写代码?
您必须检查输入的维度:
x = [1, 2, 3]
% or
x = [1; 2; 3]
new = 0;
% flexible concatenation
y = cat(~(size(x,1) > 1) + 1, new ,x)
Run Code Online (Sandbox Code Playgroud)
d = size(x,1) > 1 % check if column (=1) or row vector (>1)
z = ~(d) + 1 % results in either 1 or 2 for column or row vector
% as input for cat
y = cat(z, new ,x) % concatenate in correct dimension
Run Code Online (Sandbox Code Playgroud)
或者isrow按照ThomasIsCoding's answer 中的建议使用,但我想它几乎是一样的:
z = isrow(x) + 1;
Run Code Online (Sandbox Code Playgroud)
您应该以任何方式isvector检查输入是否实际上是向量而不是矩阵。但实际上我建议将任何输入、行或列向量转换为列向量
x = x(:)
Run Code Online (Sandbox Code Playgroud)
允许在您的基础功能中进行组合编码。