Filter löschen
Filter löschen

Replace all numbers within a matrix

1 Ansicht (letzte 30 Tage)
Krish Desai
Krish Desai am 27 Sep. 2015
Beantwortet: Star Strider am 27 Sep. 2015
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 Kommentar
Stephen23
Stephen23 am 27 Sep. 2015
Bearbeitet: Stephen23 am 27 Sep. 2015
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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

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

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by