can anyone explain, how following program is working?(5th step)
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
reshdev
le 20 Août 2014
Réponse apportée : Roger Stafford
le 20 Août 2014
A should be a randomly created 5 x 5 matrix whose elements are all integers ranging from 0 to 7 in such a way that
1) row 1 and column 1 have equal sums,
2) row 2 has a sum of 7 and column 2 has a sum of 0,
3) row 3 and column 3 have equal sums,
4) row 4 has a sum of 0 and column 4 has a sum of 7,
5) row 5 and column 5 have equal sums,
6) its diagonal elements are all zeros, and
7) all column and row sums are 7 or less,
function test
A = zeros(4);
for k = 1:7
p = randperm(4); % <-- This is the source of randomness
for ix = 1:4
A(p(ix),ix) = A(p(ix),ix) + 1; **..,please explain this step**
end
end
A = [A(:,1),zeros(4,1),A(:,2:4)]; % Insert a column of four zeros
A = [A(1:3,:);zeros(1,5);A(4,:)]; % Insert a row of five zeros
A(1,1) = 0; A(3,3) = 0; A(5,5) = 0; % Set non-zero diagonal elements to 0
disp(A);
end
1 commentaire
Roger Stafford
le 20 Août 2014
Modifié(e) : Roger Stafford
le 20 Août 2014
You've changed your question, Reshdev. That last step reduces the first, third, and fifth diagonal elements in A to zero. Since they are on the diagonal, that reduces each of the corresponding row and column sums by the same amounts and leaves them still equal as you requested.
Réponse acceptée
Roger Stafford
le 20 Août 2014
The 'randperm' function is generating random permutations of the sequence, 1,2,3,4. For example suppose it generate p = 4,3,1,2. Then in the inner for-loop with ix = 1, we have p(ix) = 4. Hence
A(p(ix),ix) = A(p(ix),ix) + 1
is doing this:
A(4,1) = A(4,1) + 1;
It is adding 1 to the element of A in the fourth row of the first column. Then the next three steps are:
A(3,2) = A(3,2) + 1
A(1,3) = A(1,3) + 1
A(2,4) = A(2,4) + 1
After those four steps you have
A = [0 0 1 0;
0 0 0 1;
0 1 0 0;
1 0 0 0]
Each row sum and each column sum is now 1. That is the property that any permutation, p, has. It would always leave you with equal row and column sums. When the outer loop is finished, all row and column sums are exactly 7.
Subsequent steps are of course meant to alter that situation.
Plus de réponses (1)
Roger Stafford
le 20 Août 2014
If you prefer vectorized solutions, I could just as well have put the solution in this form:
[~,p] = sort(rand(4,7));
A = accumarray([reshape(p+(p>3),[],1),repmat([1,3:5]',7,1)],1);
A(1:12:end) = 0;
0 commentaires
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!