Under the constraints that you have to use nested for loops and that this only has to work for matrices, not N-dimensional arrays with N > 2, I only see one bug (in two places) in your code.

The size function, when called with one input and one output, will return a vector with one element per dimension in the array you passed into it.

A = ones(2, 3);

szA = size(A)

B = zeros(3, 4, 5);

szB = size(B)

When you use a non-scalar (like a vector or a matrix) as one of the values in the colon operator : MATLAB will only use the first element of that non-scalar when building the colon vector.

So in your code, since your test case was a 3-by-3 matrix and size returned [3 3] for that matrix, both your loops were looping over 1:3. Since your test case had the same number of rows and columns this was fine. But if you tried a non-square matrix as a test case, it wouldn't work correctly.

C = [4, 5, -1; -7, 10, 9];

D = [C; C];

If you call size with two input arguments, the output will be a scalar that is the size of the matrix in that dimension.

B = zeros(3, 4, 5);

colsB = size(B, 2)

Or you can call size with one output argument per dimension of the array.

B = zeros(3, 4, 5);

[nrows, ncols, npages] = size(B)

There's some trickiness if the number of outputs is different than the number of dimensions, so I'd recommend the two input and one output form of size.

As a stylistic suggestion, I recommend using variable names that show the meaning of what's stored in those variables. To me, m and d don't really mean anything and so if this code were longer you might lose track of what they represent. But if you named them whichRow and whichCol, it is a bit more typing (though tab completion can help offset that) but it's much clearer to anyone even glancing at your code what they represent.

## Best Answer