Array indices must be positive integers or logical values.
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
h = 0.2;
T = 4:h:8
X_s=[5.87 -4.23 -2.55 -0.89 0.67 2.09 3.31 4.31 5.06 5.55 5.78 5.77 5.52 5.08 4.46 3.72 2.88 2.00 1.10 .23 -0.59]
for X=4.2:0.2:7.8
k=[X]
x=(((k/(0.2))-(4/(0.2))))+1
V = ((X_s((x)+1))-(X_s((x)-1)))/(2*h)
end
Trying to get the for loop to spit out an array of answers for a central diffrencing problem but cannot get the loop to run without an array error. when I do the math I'm seeing whole positive integers being imputed. Not sure whats going on and would appreciate help.
0 commentaires
Réponse acceptée
Matt J
le 9 Juil 2021
Modifié(e) : Matt J
le 9 Juil 2021
Since x is not an integer, you cannot use it to look up an entry in a vector X_s(x). Perhaps the following is what you really want?
h = 0.2;
X_s=[5.87 -4.23 -2.55 -0.89 0.67 2.09 3.31 4.31 5.06 5.55 5.78 5.77 5.52 5.08 4.46 3.72 2.88 2.00 1.10 .23 -0.59];
V=(X_s(3:end)-X_s(1:end-2))/(2*h)
2 commentaires
DGM
le 10 Juil 2021
Modifié(e) : DGM
le 10 Juil 2021
First note that in your loop, you're not actually calculating a vector V. You're calculating V as a scalar and discarding all the results except the last one. It's assumed that's not what you intend.
Nothing in the loop depends on prior results, so the loop isn't necessary. We can look at the vectors that are being generated and look for a pattern:
h = 0.2;
T = 4:h:8;
X_s=[5.87 -4.23 -2.55 -0.89 0.67 2.09 3.31 4.31 5.06 5.55 5.78 ...
5.77 5.52 5.08 4.46 3.72 2.88 2.00 1.10 .23 -0.59];
k=4.2:0.2:7.8
x=k/0.2 - 4/0.2 + 1
So x is ostensibly integer-valued, varying from 2 to 20. Since x is used as the basis for indexing in X_s:
V = (X_s(x+1) - X_s(x-1))/(2*h)
... and the length of X_s is 21, then the above indices are equivalent to
V = (X_s((2+1):(20+1)) - X_s((2-1):(20-1)))/(2*h)
% or
V = (X_s(3:end) - X_s(1:end-2))/(2*h)
Plus de réponses (1)
G A
le 9 Juil 2021
Modifié(e) : G A
le 9 Juil 2021
floating point problem;
try to use x = round(k/0.2 - 4/0.2 + 1)
k =
4.200000000000000
x =
2
k =
4.400000000000000
x =
3
k =
4.600000000000001
x =
4
k =
4.800000000000001
x =
5.000000000000004
k =
5
x =
6
k =
5.200000000000000
x =
7
k =
5.400000000000000
x =
8
k =
5.600000000000001
x =
9
k =
5.800000000000001
x =
10.000000000000004
0 commentaires
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!