Array indices must be positive integers or logical values.

조회 수: 1 (최근 30일)
Mark Prentice
Mark Prentice 2021년 7월 10일
댓글: Mark Prentice 2021년 7월 10일
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:0.2:8 %%%need to take the first and last point off since central difffrencing doesnt work on them
k=[X];
x = round(k/0.2 - 4/0.2 + 1);
V = ((X_s((x)+1))-(X_s((x)-1)))/(2*h);
if X==4
k=[X];
x = round(k/0.2 - 4/0.2 + 1);
V = ((X_s((x)+1))-(X_s((x))))/(2*h);
end
if X==8
k=[X];
x = round(k/0.2 - 4/0.2 + 1);
V = ((X_s((x)))-(X_s((x-1))))/(2*h);
end
Velcoity=V
end
Hey there,
Im now trying to get the array to work with two end points where it can take them and redirect them to equations suited to solving them with the given data. However I find myself getting the error "Array indices must be positive integers or logical values". I've tried reorginizing my if statments to come first and that doesnt seem to work. If i change the start to 4.2 and the end to 7.8 it works like a charm but cant figure out why it wont accept the start as 4 and end as 8 and use the forward and backward diffrencing equations. Any help or knowledge helps and thank you for looking.

채택된 답변

Walter Roberson
Walter Roberson 2021년 7월 10일
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]
X_s = 1×21
-5.8700 -4.2300 -2.5500 -0.8900 0.6700 2.0900 3.3100 4.3100 5.0600 5.5500 5.7800 5.7700 5.5200 5.0800 4.4600 3.7200 2.8800 2.0000 1.1000 0.2300 -0.5900
nX = length(X_s);
for x = 1 : nX
if x == 1
V = ((X_s((x)+1))-(X_s((x))))/(2*h);
elseif x == nX
V = ((X_s((x)))-(X_s((x-1))))/(2*h);
else
V = ((X_s((x)+1))-(X_s((x)-1)))/(2*h);
end
Velocity(x) = V;
end
plot(1:nX, X_s, 'k-', 1:nX, Velocity, 'b--')

추가 답변 (1개)

G A
G A 2021년 7월 10일
When x=1, then X_s(x-1) = X_s(0), which is not allowed in Matlab
x =
1
x =
1
x =
2
x =
3
x =
4
x =
5
x =
6
x =
7
x =
8
x =
9
x =
10
x =
11
x =
12
x =
13
x =
14
x =
15
x =
16
x =
17
x =
18
x =
19
x =
20
x =
21
x =
21
  댓글 수: 3
Walter Roberson
Walter Roberson 2021년 7월 10일
Yes, but you have
V = ((X_s((x)+1))-(X_s((x)-1)))/(2*h);
before you test whether X == 4
Mark Prentice
Mark Prentice 2021년 7월 10일
Yes, I've been rearranging the whole system of 3 equations in every and all configurations. Such as putting it last however I'm still getting the error. I'm wondering if theres another variable im missing or a function that makes the 4 value on go into one equation ( if im useing the if functions right). But yes you are correct V = ((X_s((x)+1))-(X_s((x)-1)))/(2*h); should not be first.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 General Applications에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by