Solve "Index exceeds the number of array elements (1)", "Vectors must be the same length." errors
1 次查看(过去 30 天)
显示 更早的评论
I'd like to solve those problems from under coding using A, B, and C relationships. If equation error can't be fixed, "B(i+1)=B(i)+((h.*q)/(k*T*E))*C(i)" can be used.
a = 0;
b = 1;
n = 110;
k = 8.61733*10^(-5);
T = 300 ;
q = 1.60218*10^(-19);
E = 8.8542*10^(-12)
x= linspace(a,b,n);
h= x(2)-x(1);
A = zeros(size(x));
B = zeros(size(x));
for i = 0:n-1
A(0)=3;
B(0)=1;
C(i)=2*x(i)+3;
A(i+1)=A(i)-h.*B(i)-(0.5.*h.^2*q.*C(i))./(k*T*E);
B(i+1)=B(i)+((h.*q)/(k*T*E))*0.5*(C(i)+C(i+1));%equation error
end
plot(transpose(x),A,'.')
1 个评论
Tanmay Das
2020-7-15
Hi. Can you please try starting the index from 1 instead of 0 and go upto n in the for loop?
采纳的回答
Walter Roberson
2020-7-15
a = 0;
b = 1;
n = 110;
k = 8.61733*10^(-5);
T = 300 ;
q = 1.60218*10^(-19);
E = 8.8542*10^(-12)
x= linspace(a,b,n);
h= x(2)-x(1);
A = zeros(size(x));
B = zeros(size(x));
A(0+1)=3;
B(0+1)=1;
for i = 0:n-1
C(i+1)=2*x(i+1)+3;
A(i+1+1)=A(i+1)-h.*B(i+1)-(0.5.*h.^2*q.*C(i+1))./(k*T*E);
B(i+1+1)=B(i+1)+((h.*q)/(k*T*E))*0.5*(C(i+1)+C(i+1+1));
end
plot(transpose(x),A,'.')
12 个评论
Walter Roberson
2020-7-20
Which theoretical equation are you comparing to, and which result from your program are you comparing it to?
How do you know when you have reached and adequate solution?
更多回答(1 个)
Tanmay Das
2020-7-15
Hi,
I have the understanding that you are facing trouble in indexing of arrays. Unlike C++ or Python, indexing starts from 1 in MATLAB. So if you write A(0), then it will throw error. The following code may be useful for your understanding:
a = 0;
b = 1;
n = 110;
k = 8.61733*10^(-5);
T = 300 ;
q = 1.60218*10^(-19);
E = 8.8542*10^(-12)
x= linspace(a,b,n);
h= x(2)-x(1);
A = zeros(size(x));
B = zeros(size(x));
A(1)=3;
B(1)=1;
C = 2*x + 3
for i = 1:n-1
A(i+1)=A(i)-h.*B(i)-(0.5.*h.^2*q.*C(i))./(k*T*E);
B(i+1)=B(i)+((h.*q)/(k*T*E))*0.5*(C(i)+C(i+1));%equation error
end
plot(transpose(x),A,'.')
Also please note that similar operations on each element of array can be done at once in MATLAB and do not require to run a loop like in case of C.
C = 2*x + 3
Hope that helps!
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!