sum of all matrix elements equal to zero

5 views (last 30 days)
Hi, kindly check the code. I want a matrix whose total sum of elements is zero.......
regards
clc
clear all
format compact
nrows = 5
afm_array = ones(nrows)
theta = round((rand(5)-0.5) * 360)
theta(5,5) = 0
alpha = sum(sum(theta))-360
theta(5,5) = - alpha
theta_new = theta
add_theta = sum(sum(theta_new))

Accepted Answer

John D'Errico
John D'Errico on 13 May 2016
Well, you COULD just subtract off the sum of the matrix, divided by the number of elements in the matrix.
theta = theta - sum(theta(:))/numel(theta);
That is actually not a terribly good way to solve the problem, for reasons I don't feel like going into here, because it will take a lot of explanation. Just accept it works, but is not the best solution.
Better would be to use a tool like randfixedsum, from the file exchange.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!