MATLAB: How to add element in a vector

functionMATLABmatrix

i want to create a 20 random binary matrix where in every one from these matrix i want to do some calculation
after that i want to find the min value from all matrix and after that i want to return the matrix which have the min value
like that
A = [ 1 1 0 1
0 0 1 0
1 0 1 0
0 1 1 0 ]
for k=1:20
s = randi([0 1],n,m)
z(k) = (sum(sum(A ~= s)));
end
then i want to find the min value from all matrix and after that return the matrix which have the min value like that
if z = [ 4 4 5 3 2 5 7 8 9 7 9 7 8 9 7 5 4 1 7 ]
then i want from the function to return the matrix number 19 because the value of 19 is the min value like that
s19 = [ 1 1 0 1
0 0 1 0
0 0 1 0
0 1 1 0 ]

Best Answer

The simplest way would be to generate all 20 random matrices in one go as pages of a 3D matrix:
A = [ 1 1 0 1
0 0 1 0
1 0 1 0
0 1 1 0 ];
nummatrices = 20;
S = randi([0 1], [size(A), nummatrices]); %Sk is S(:, :, k)
z = squeeze(sum(sum(bsxfun(@ne, S, A), 1), 2)) %compare A to each page with bsxfun and sum in two dimensions
[zmin, minidx] = min(z) %find location of minimum in z
Smin = S(:, :, minidx) %and return that page
Related Question