Search code examples
matlabvectorsumaddition

How to change all elements of a vector V to achieve the condition sum(V) equal with a upper and lower boundaries?


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

Solution

  • Try making a variable(maybe call it sumV) to store the sum of everything in V and another variable which stores 1/sumV. This variable would be what you use to change the elements of the vector. You could use lp and up to check that the values in V didn't go over or under your bounds with a for loop that went over all the elements in v.

    Some psuedo code:

    1. for i = 1:length(V)

    2. if statement checking if V(i) was less than the lower boundary 'lp'

    3. update any values less than 'lp' to 'lp'

    4. if statement checking if V(i) was greater than the upper boundary 'up'

    5. update any values greater than 'up' to 'up'

    6. end of for loop

    7. now sum all elements in V to a variable e.g. sumV

    8. divide 1 by sumV to get your scale factor which is used to modify the contents of V

    9. loop over all elements in V and times them all by the scale factor*

    Hope that answers your question :)