sum of all matrix elements equal to zero

6 次查看(过去 30 天)
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))

采纳的回答

John D'Errico
John D'Errico 2016-5-13
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.

更多回答(0 个)

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by