Array indices must be positive integers or logical values.
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Matt J
2021-7-9
编辑:Matt J
2021-7-9
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 个评论
DGM
2021-7-10
编辑:DGM
2021-7-10
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)
更多回答(1 个)
G A
2021-7-9
编辑:G A
2021-7-9
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!