Could anyone tell me how to replace the numbers of the matrix such that the addition of the numbers is fixed to a particular value

1 次查看(过去 30 天)
For the following matrix
D=[1 2 3 0 0 6;
7 8 9 0 0 3;
4 5 6 0 0 7]
if i add the numbers it results in 61.
but how can i change the numbers of the matrix such that the addition of numbers results in 70.
  3 个评论

请先登录,再进行评论。

采纳的回答

Walter Roberson
Walter Roberson 2018-1-29
new_D = D .* 70/61;
But perhaps you are looking for a solution such as:
idx = find(D); %where the non-zero elements are
num_used = length(idx);
for K = 1 : 70-61
ridx = idx(randi(num_used));
D(ridx) = D(ridx) + 1;
end
This adds 1 to random entries in D until the total is the required total. The procedure deliberately avoids the entries that are 0, guessing that those are some-how special for you and need to be left at 0 (but for all we know, perhaps it is the other way around and you want to add only to the entries that start out as 0.) The random selection can end up selecting the same location multiple times to add to. This is because the number of 1's that need to be added might be more than the number of non-zero entries, so you might be needing to add more than 1 to some entries anyhow.
  3 个评论
Walter Roberson
Walter Roberson 2018-1-29
You can rename K to "iteration_number" if you prefer.
The code figures out the difference between the current sum and the sum that is needed. That difference might be negative (too many values are set) or positive (more values need to be set).
If it is positive, then it does increase_by iterations, where each iteration it adds 1 to one of the counters. After having done increase_by iterations each adding 1, the total must be increase_by higher now, so the total of D must now be the desired value.
If it is negative, then the code does abs(increase_by) iterations, where each iteration it subtracts 1 from one of the counters. After having done abs(increase_by) iterations each subtracting 1, the total must be abs(increase_by) lower now, so the total of D must now be the desired value.
For your example matrix, it needs to use the decrease logic. It needs to do that because you indicated that no matrix element must be less than 3, so we have to immediately set those 0's and 1's and 2's to be 3. After we have imposed your minimum of 3, the matrix has a total that is higher than is desired, so values have to be subtracted off until you reach the total you want. The code avoids subtracting off any location that is a 3, because doing that would violate your constraint that values must be at least 3.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Preprocessing 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by