MATLAB Answers

rand matrix for FM

1 view (last 30 days)
Offroad Jeep
Offroad Jeep on 31 Mar 2015
Edited: James Tursa on 1 Apr 2015
Hi all,I want to generate a random matrix so that the sum of all the elements is zero. I mean the random numbers are so selected that the total sum of the matrix goes to zero.Regards. Early reply will be highly appreciated.
for example
a = rand(3)
a =
0.3000 0.5000 0.8000
-0.1000 -0.4000 -0.6000
-0.4000 0.8000 -0.9000
>> sum(sum(a))
ans =
0
  2 Comments
Offroad Jeep
Offroad Jeep on 31 Mar 2015
Both for integer and decimals.............

Sign in to comment.

Answers (3)

Roger Stafford
Roger Stafford on 31 Mar 2015
Edited: James Tursa on 1 Apr 2015
If your x values are subject to common upper and lower bounds, you can use my 'randfixedsum' function in the File Exchange, located at:
It is designed to give a uniform distribution on the hyperplane of values satisfying the condition of a predetermined sum - in your case a sum of zero.
  1 Comment
John D'Errico
John D'Errico on 31 Mar 2015
And of course, this is the best answer.

Sign in to comment.


Zoltán Csáti
Zoltán Csáti on 31 Mar 2015
I recommend you to generate the matrix of the required size and then modify one element of it so that the sum holds. E.g.
A = rand(3);
totalSum = sum(sum(A));
A(end,end) = A(end,end) - totalSum;
Then the sum will give you zero, aside from the round-off error.
  2 Comments
Zoltán Csáti
Zoltán Csáti on 1 Apr 2015
Yes, you are right I didn't think of this aspect.

Sign in to comment.


Brendan Hamm
Brendan Hamm on 31 Mar 2015
How about you create a random matrix and then subtract from each element the sum(matrix(:))/numel(matrix).
n = 4;
A = rand(4);
s = sum(A(:))/numel(A);
A = A - s;
sum(A(:))
  5 Comments
Brendan Hamm
Brendan Hamm on 1 Apr 2015
They are currently U([-c c]) where c i s the sum of the originally sampled elements divided by the number of elements. You want them to be U([-1 1]), then just divide by the magnitude of the largest resulting element now:
A = A / max(abs(A(:)));

Sign in to comment.

Products

Community Treasure Hunt

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

Start Hunting!