MATLAB: Could anyone help me to solve the following issue

matrix manipulation

A=[4.7908 5.0104 5.1329 5.3186 5.3094 5.3070 5.4452 5.5001;
0.0958 0.0994 0 0 0.1848 0.2020 0.1851 0.2146;
0.0848 0 0.1469 0.1859 0.1767 0.1854 0.1856 0.1648;
0 0 0 0 0 0 0 0;
0 0.0896 0.1619 0.1351 0 0 0 0;
0 0 0 0 0 0 0 0]
In row 4 and row 6 all numbers are found to be zero.
Could anyone help me how to rearrange the existing numbers in each column such that each row should contain at least one non zero value and each column should containg three non zero values.

Best Answer

Here is one way. Just brute force scramble the array until it meets the criteria:
A=[4.7908 5.0104 5.1329 5.3186 5.3094 5.3070 5.4452 5.5001;
0.0958 0.0994 0 0 0.1848 0.2020 0.1851 0.2146;
0.0848 0 0.1469 0.1859 0.1767 0.1854 0.1856 0.1648;
0 0 0 0 0 0 0 0;
0 0.0896 0.1619 0.1351 0 0 0 0;
0 0 0 0 0 0 0 0];
[rows, columns] = size(A)
tryAgain = true;
maxIterations = 1000000;
loopCounter = 0;
while tryAgain && loopCounter < maxIterations
randomIndexes = randperm(numel(A));
A = reshape(A(randomIndexes), rows, columns);
% Check that each row has at least 1 non-zero value
rowsOK = sum(any(A, 2)) == rows;
% Check that each column has at least 3 non-zero values
columnsOK = all(sum(A ~= 0, 1) >= 3);
loopCounter = loopCounter + 1;
if rowsOK && columnsOK
break
end
end
fprintf('Found this A after %d iterations:\n', loopCounter);
A