Replace all numbers within a matrix

1 次查看(过去 30 天)
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
  1 个评论
Stephen23
Stephen23 2015-9-27
编辑:Stephen23 2015-9-27
I formatted your code for you, but in future please do it yourself by selecting the code text and clicking the {} Code button that you will find above the text box.
Please do not put blank lines between every line of your code.

请先登录,再进行评论。

采纳的回答

Star Strider
Star Strider 2015-9-27
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by