2D array in for loop problem

130 visualizzazioni (ultimi 30 giorni)
Suha Ismail
Suha Ismail il 7 Mag 2020
Commentato: Suha Ismail il 7 Mag 2020
N=40
a=0.9
x =zeros(41,41)
for k=0:N
for col = 0:41
for row = 0:41
x(row,col)=a.^(k+k)*1;
end
end
end
What is the problem (error: x(0,_): subscripts must be either integers 1 to (2^31)-1 or logicals)?

Risposta accettata

Akihumi
Akihumi il 7 Mag 2020
Modificato: Akihumi il 7 Mag 2020
Unlike Python, C, C++ and other programming languages, Matlab starts the matrix index with 1 instead of 0.
So just change the first number then it should be working without having error.
N=40
a=0.9
x =zeros(41,41)
for k=1:N
for col = 1:40
for row = 1:40
x(row,col)=a.^(k+k)*1;
end
end
end
However, 1st to 39th iteration of k for loop might be overwritten and x would only show the result of 40th iteration of k for loop... And the final result of x would only be a 40-by-40 matrix filled with the value of 0.9^80=2.1847e-4 for all elements...
Which could be simplifed as
N=40
a=0.9
x=a^(2*N)*ones(N)

Più risposte (0)

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by