How to change all elements of a vector V to achieve the condition sum(V) equal with a upper and lower boundaries?
2 次查看(过去 30 天)
显示 更早的评论
I have a vector V, for example, V=[0.1 0.002 0.5 0.2 0.1 0.003 0.4].
The boundaries of all elements of the matrix V should always be between 0.01 and 0.8.
I want to create a function to change the elements of the vector V where the sum of V becomes equal to one.
I am looking to create a function in Matlab V= Editor(V, lp, up );
- where lp: is the lower boundary, in my example 0.01
- and up: is the upper boundary, in my example 0.8
采纳的回答
DGM
2022-12-29
编辑:DGM
2022-12-29
Well with requirements like that, I guess this is fair game.
% input
V = [0.1 0.002 0.5 0.2 0.1 0.003 0.4];
% parameters
limits = [0.01 0.8];
outsum = 1;
% constraints cannot be met generally
if outsum/numel(V) < limits(1)
error('too many elements')
elseif outsum/numel(V) > limits(2)
error('too few elements')
end
% i'm going to be super lazy
sumv = sum(V);
while abs(sumv-outsum) > 1E-9 % or some arbitrary tolerance
scale = outsum/sumv;
V = min(max(V*scale,limits(1)),limits(2));
sumv = sum(V);
end
V
4 个评论
DGM
2022-12-29
Nothing about the question suggested that the output was random. If the output is random, what's the purpose of V? Does the output depend on V? If so, how?
更多回答(2 个)
Walter Roberson
2022-12-29
if the requirement is that you apply a linear transform to the elements of V producing a new vector W such that sum(W) == 1 and the elements respect the upper and lower bounds, then the problem cannot generally be solved.
A simple proof is that V might consist of more than 100 elements. With the minimum being 0.01 then the sum would have to be more than 100*0.01 == 1
2 个评论
Walter Roberson
2022-12-29
That said
syms a
w = (v-0.01)*a + 0.01;
sola = solve(sum(w)==1,a);
w = simplify(w, a, sola)
sola can be expressed analytically so it can be computed without the symbolic toolbox
Walter Roberson
2022-12-29
each entry w(k) is a*(v(k)-0.01)+0.01 which is a*v(k) - a*0.01 + 0.01
Let N = length(v). Then sum(w) is a*sum(v) - N*a*0.01 + N*0.01 = a*(sum(v) - N*0.01) + N*0.01. The unknown is a and the sum is 1 so a = (1-N*0.01) / (sum(v) - N*0.01)
Note that if the original values in v could be negative or less than 0.01 then the denominator could be 0 which would be a problem. If the denominator is negative because entries in v are less than 0.01 then I do not promise at the moment that the transformed values are within the required limits.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!