Speeding up Binary Matricies Generation with given conditions
Ältere Kommentare anzeigen
Need help speeding up my code that produces 3x3 Binary Matrix only if it meets all the fixed row and column sums. It currently times out a lot before it generates the matrix and I need to get it faster to modify it for a 5x5. Also want to mention that there is probably a few things wrong in my code, and that is because I am a beginner a small idea on how I am forcing it to work.
rows = 3;
columns = 3;
C1=2; %Fixed Column Sums
C2=3;
C3=1;
R1=1; %Fixed Row Sums
R2=2;
R3=3;
% Initialize matrix.
m=randi([0 1],rows,columns);
for k=1:rows,
end
runtest = 0 ;
while runtest < 10000000 ;
runtest = runtest + 1 ;
% randomly swap columns
for k=1:columns,
p = randperm(rows);
m(k,:) = m(k,p);
end
if (sum(m(:,[1])) == C1) && (sum(m(:,[2])) == C2) && (sum(m(:,[3])) == C3)...
&& (sum(m([1],:)) == R1) && (sum(m([2],:)) == R2) && (sum(m([3],:)) == R3);
break ;
end
end
R_1 = m(1,1) + m(1,2) + m(1,3);
R_2 = m(2,1) + m(2,2) + m(2,3);
R_3 = m(3,1) + m(3,2) + m(3,3);
%Summing up all the Rows into a array to read
RowsSums= [ R_1 R_2 R_3 ];
C_1 = m(1,1) + m(2,1) + m(3,1);
C_2 = m(1,2) + m(2,2) + m(3,2);
C_3 = m(1,3) + m(2,3) + m(3,3);
%Summing up all the Columns into a array to read
ColumnSums= [ C_1 C_2 C_3 ];
if runtest < 10000000
m
RowsSums
ColumnSums
else
disp('No matrix found within time') ;
end}
Akzeptierte Antwort
Weitere Antworten (0)
Kategorien
Mehr zu Random Number Generation finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!