B = [150 90; -100 -120; -80 130; 140 -70; 60 120; -90 -130];
这些是6个坐标的值。我想从这些坐标计算平均距离。我需要使用此功能。但是我不能从函数中的每个坐标分配第二个值。
davg = 0;
m = 0;
c=0.707;
B=[150 90; -100 -120; -80 130; 140 -70; 60 120; -90 -130];
for j = 1:6
for i = 1:2
m =m+((sqrt(B(j,i)^2+B(j,i+1)^2))/c);
end
end
davg = m/6;
答案 0 :(得分:1)
由于您已经计算了平方元素的总和,因此不需要内部循环。对于二维情况,您可以这样写:
m = m + ((sqrt(B(j, 1).^2 + B(j, 2).^2)) / c);
对于n维情况,您可以通过以下方式重新编写循环:
% Input and parameters.
davg = 0;
m = 0;
c = 0.707;
B = [150 90; -100 -120; -80 130; 140 -70; 60 120; -90 -130];
% Get number of data points and dimensionality.
nPoints = size(B, 1);
nDim = size(B, 2);
% Iterate every data point.
for j = 1:nPoints
% Calculate sum of squared elements in loop (for arbitrary dimensionality).
temp = 0;
for i = 1:nDim
temp = temp + B(j, i).^2;
end
% Apply square root afterwards.
m = m + sqrt(temp) / c;
end
% Calculate average.
davg = m / nPoints
我知道,您写的是,您必须使用上述公式,但是,整个计算可以简化为:
% Input and parameters.
c = 0.707;
B = [150 90; -100 -120; -80 130; 140 -70; 60 120; -90 -130];
% Calculate average.
davg = mean(vecnorm(B, 2, 2) / c)
答案 1 :(得分:0)
所有矢量的加权哑应该没问题吗?
sum(sqrt(sum(B.^2,2)))/size(B,1)