How to change all elements of a vector V to achieve the condition sum(V) equal with a upper and lower boundaries?
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Rahim Rahim
el 29 de Dic. de 2022
Comentada: DGM
el 29 de Dic. de 2022
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
4 comentarios
Respuesta aceptada
DGM
el 29 de Dic. de 2022
Editada: DGM
el 29 de Dic. de 2022
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 comentarios
DGM
el 29 de Dic. de 2022
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?
Más respuestas (2)
Walter Roberson
el 29 de Dic. de 2022
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 comentarios
Walter Roberson
el 29 de Dic. de 2022
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
el 29 de Dic. de 2022
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.
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!