MATLAB: Replace all numbers within a matrix

matrix arraymatrix manipulation

I'm trying to change all the numbers in a matrix between 1: n^2
My code is:
function output = IsMagic(n)
A= zeros(n);
r=1;
c=1;
row_index = 0;
while row_index <= r
col_index=0;
while col_index <= c
A(r,c) = randi(1*n^2);
col_index=col_index + 1;
end
row_index= row_index +1;
end
output=A;
end

Best Answer

I’m not quite certain I understand what you want to do. This will produce a (n x n) matrix with your random integers:
A= zeros(n);
r=n;
c=n;
row_index = 1;
while row_index <= r
col_index=1;
while col_index <= c
A(row_index,col_index) = randi(1*n^2);
col_index=col_index + 1;
end
row_index= row_index +1;
end
One problem is that you set ‘r’ and ‘c’ both to 1, so you were only ever addressing A(1,1). I changed those to n, and the row and column references for ‘A’ to ‘row_index’ and ‘col_index’. I also started those at 1 instead of 0. The code now produces the matrix I believe you want to create. Change the code as necessary so it does what you want.