Index in position 1 is invalid but I need w(0,j), w(0,0), and w(m,0)

2 vues (au cours des 30 derniers jours)
LightFury Yeji
LightFury Yeji le 6 Fév 2021
Commenté : LightFury Yeji le 6 Fév 2021
I am following an algorithm for wave equations (shown on the pic). I get the error "Index in position 1 is invalid. Array indices must be positive integers or logical values." What do I do, if w(0,j), w(0,0), and w(m,0) are needed? Also, in this line "wij(i,1)=(1-lambda^2)*f(i*h)+(lambda^2/2)*(f((i+1)*h)+f((i-1)*h))+k*g(i*h);" i get the error "Unable to convert expression containing symbolic variables into double array." Help would be very much appreciated, thanks.
This is my program:
%STEP0
l=1; %endpoint
T=1; %maximum time
alpha = 2; %constant
m=10;
N=20;
syms f(x) g(x,t)
f(x)=sin(pi*x);
g(x)=(sin(pi*x))*(cos(2*pi*t));
%STEP1
h=l/m;
k=T/N;
lambda=k*alpha/h;
%STEP2
for j=1:N
wij(0,j)=0;
wij(m,j)=0;
end
%STEP3
wi(0,0)=f(0);
wi(m,0)=f(l);
%STEP4
for i=1:m-1
wij(i,0)=f(i*h);
wij(i,1)=(1-lambda^2)*f(i*h)+(lambda^2/2)*(f((i+1)*h)+f((i-1)*h))+k*g(i*h);
end
%STEP5
for j=1:N-1
for i=1:m-1
wij(i,j+1)=2*(1-lambda^2)*w(i,j)+lambda^2*(wij(i+1,j)+wij(i-1,j))-wij(i,j-1);
end
end
%STEP6
for j=0:N
t=j*k;
for i=0:m
x-i*h;
fprintf( '%.1f %.1f %.10f',x,t,wij(i,j))
end
end

Réponse acceptée

Jos Jordan
Jos Jordan le 6 Fév 2021
Modifié(e) : Jos Jordan le 6 Fév 2021
I'm pretty sure the answer here is that unlike most other languages, MATLAB starts indexing at 1, not 0. So for example in the code you wrote:
%STEP 2
for j=1:N
wij(1,j)=0;
wij(m,j)=0;
end
would give the desired result - you would then have to change the others to have an index of 1 instead of 0.
  3 commentaires
Jos Jordan
Jos Jordan le 6 Fév 2021
I think so - in the problem everything is indexed from 0, so you want to index from 1 - if you think about what you're doing carefully you should be able to see which parts you need to add 1 to.
In Step 4 you are doing:
which in your code is:
for i=1:m-1
wij(i,1)=f(i*h);
wij(i,2)=(1-lambda^2)*f(i*h)+(lambda^2/2)*(f((i+1)*h)+f((i-1)*h))+k*g(i*h);
end
as you starting the index of the second subscript at 1 as oppose to 2.
By the looks of it, you should also set
for i=2:m
wij(i,1)=f(i*h);
wij(i,2)=(1-lambda^2)*f(i*h)+(lambda^2/2)*(f((i+1)*h)+f((i-1)*h))+k*g(i*h);
end
changing the value of i you are looping over, as again you are adding one to the index there as in the problem it states:
so you want to be iterating from the second index of the i in your code. If you cange the rest of it - it should work, I believe. If not I'll test it and see.
LightFury Yeji
LightFury Yeji le 6 Fév 2021
Thank you so much :)

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Mathematics 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!

Translated by