微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

改变向量的大小

如何解决改变向量的大小

我正在尝试从数组中的向量扩展或减去幅度。调用函数代码是:

v_set = {[1;0],[0;2],[1;1]};
v_extensions = [1,-.5,1];

v_set_extended = vector_set_extend(v_set,v_extensions);

函数本身在下面。我已经将x和y的幅度都增加了,但是我想让它在向量指向的方向上增加幅度,如果那是有道理的。

function v_set_extended = vector_set_extend(v_set,v_extensions)
% Takes a set of vectors and a set of lengths by which to extend them.
% Returns a set of extended vectors
%
% Inputs: 
%
%   v_set: a cell array,each element of which is a vector
%
%   v_extensions: a vector of the same dimensions as v_set,containing
%       lengths which should be added to the vectors
%
% Outputs:
%
%   v_set_extended: cell array of the same size as v_set,each element of
%       which is the vector with its new length

    %%%%%%%%
    % Use the 'cell' and 'size' commands to create the output
    % v_set_extended as an empty cell of the same size as v_set
    v_set_extended = cell(size(v_set))
    
    %%%%%%%%
    % Loop over the vectors and extensions,adding the extension to the
    % length of the vector,and then storing the result in the
    % corresponding entry of v_set_extended
    for idx = 1:numel(v_set_extended)
        v_set_extended{idx} = v_set{idx}+v_extensions(idx);
    end
end

解决方法

这主要是三角学问题。您有向量,我们将其称为v,其成分为v_xv_y。现在让我们说,您想在向量的幅度上加上w

v的大小为sqrt(v_x^2 + v_y^2),其角度为theta = tan(v_y/v_x)。 然后,您想要做的是创建一个幅度为m = sqrt(v_x^2 + v_y^2) + w但方向相同的新矢量。一旦知道了新的大小,角度便是相同的,向量的新成分是v1_x = m*cos(theta)v1_y = m*sin(theta)

实施此操作没有任何问题,只需注意Matlab中sin / sind之间的区别。

,

该解决方案非常简单,但是由于您正在使用单元阵列,因此解决方案更加复杂。请避免使用单元格数组,并尽可能选择普通数组。所以首先我们将v_set转换成矩阵:

v_mat = cell2mat(v_set)

然后您要扩展向量,以便将新向量的大小扩展某个值。首先计算向量的大小:

mag_v_mat = vecnorm(v_mat);

最后一次制作所有矢量:

v_extended = v_mat.*(mag_v_mat+v_extensions)./mag_v_mat;

点分运算符用于将向量中的操作向量化。

一行可以写成:

v_extended = cell2mat(v_set).*(1+v_extensions./vecnorm(cell2mat(v_set)));
,

请参考注释以获取解释,坚持当前结构的简单方法是仅计算单位矢量并对其进行缩放,而不是直接添加扩展名...

for idx = 1:numel(v_set_extended)
    % Compute the unit vector (magnitude 1) in the same direction
    uvec = v_set{idx} / vecnorm(v_set{idx});
    % Create a vector of the extension length in the unit direction
    ext = uvec * v_extensions(idx);
    % Add the extension
    v_set_extended{idx} = v_set{idx} + ext;
end

您可以通过验证vecnorm(幅度)值来进行健全性检查

cellfun( @vecnorm,v_set )          % = [1,2.0,1.4142]
cellfun( @vecnorm,v_set_extended ) % = [2,1.5,2.4142]
                         % difference = [1,-0.5,1]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。