"Subscript indices must either be real positive integers or logicals"

5 次查看(过去 30 天)
I'm trying to write a script for the Linear Finite-Difference formula using my textbook's pseudo code (Numerical Analysis, Burden, 10E). Here is what I have so far and my issue. The problem is y'' = -(x+1)*y' + 2*y + (1-x^2)*exp(-x), 0<=x<=1, y(0) = -1, y(1) = 0, h=.1. When I get down to the line that has a(1) = 2 + (h^2)*q(x), it gives me this error "Subscript indices must either be real positive integers or logicals." I'm confused because my index is 1 which is a real positive integer. Any help would be appreciated. Code so far is below.
function [x,w] = linear_fin_diff(a,b,alpha,beta,h)
%Linear Finite-Difference
p = @(x) -x+1;
q = 2;
r = @(x) (1-x^2)*exp(-x);
N = ((b-a)/h)-1;
x = a + h;
a(1) = 2 + (h^2)*q(x);

回答(1 个)

Star Strider
Star Strider 2019-4-2
Your index may be postive, however since ‘q’ is not a function, MATLAB interprets the ‘q(x)’ in this assignment:
a(1) = 2 + (h^2)*q(x);
as a subscript reference to ‘q’. This will also throw an error if ‘x’ here is anything other than 1.
  2 个评论
Nicholas Boccella
Thanks, that makes sense. I was able to fix it. Later on, I have the following code to find a,b,c,d (variables I declared) following the code above. Ho
for i = 2:N-1
x = a + i*h;
a(i) = 2 + h^2 * q;
b(i) = -1 + (h/2)*p(x);
c(i) = -1 - (h/2)*p(x);
d(i) = -(h^2)*r(x);
end
It calculates a(2), but then when I get to b (and when I comment out b, it happens to c and d as well), I get the following error: "In an assignment A(:) = B, the number of elements in A and B must be the same."
I'm confused because I am asking the loop to spit out a single number and put it in the ith spot in those vectors. Also, initially I wrote the following code above that for loop:
a = zeros(N,1);
b = zeros(N,1);
c = zeros(N,1);
d = zeros(N,1);
This way, I already declared the size of those vectors. I'm confused why I am not getting a number. Thanks.
Star Strider
Star Strider 2019-4-2
When you subscript your variables, you ‘grow’ them as vectors, so assigning a vector to a scalar result will throw that error. I’m not sure what you’re doing, although if you remove your subscripts, the code does what you want it to. You can always keep track of the variables in a separate matrix (‘rec’ here) if you want.
Try this:
b = 2; % Create Constant
a = 1; % Create Constant
h = 0.1;
N = ((b-a)/h)-1;
p = @(x) -x+1;
q = 2;
r = @(x) (1-x^2)*exp(-x);
rec = zeros(N-1, 5);
for i = 2:N-1
x = a + i*h;
a = 2 + h^2 * q;
b = -1 + (h/2)*p(x);
c = -1 - (h/2)*p(x);
d = -(h^2)*r(x);
rec(i,:) = [x a b c d];
end

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Descriptive Statistics 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by