How is it possible that matlab solves two simultaneous equations which have relation to each other? I am very new with matlab and can not get it done. I want to solve several equations with the euler method bot always get errors.
1 次查看(过去 30 天)
显示 更早的评论
main code :
clear all
a=0;
b=10;
N=10;
y0=0;
h=(b-a)/N;
t(1)=a;
R(1)=1;
Pg(1)=1;
P1(1)=1;
c(1)=12;
for n=1:N;
t(n+1)=t(n)+h;
c(n+1)=c(n)+h*g(t(n),c(n));
Pg(n+1)=1.9*g(t(n),c(n));
P1(n+1)=8*R(n);
R(n+1)=R(n)+h*f(t(n),R(n)) ;
end
plot(t,R)
function g:
function g=g(t,c)
g=(45*c)/74;
function f:
function f=f(t,R)
f=(((Pg-P1)*R)/152)-60;
this is the result:
Error :Undefined function or variable 'Pg'
Error in f (line 2)
f=(((Pg-P1)*R)/152)-60
how can I asign the variable Pg and P1 to the equation in the main code
4 个评论
Andrew Newell
2015-3-12
Brendan, I think I may have caused some confusion by reformatting the code incorrectly (I have fixed the error). I think they already are in separate files. Sorry about that.
采纳的回答
Andrew Newell
2015-3-12
You could just write
Pg = 1;
but a better way, since you know how large the vector will be, is to preallocate the memory:
Pg = ones(1,N+1);
2 个评论
Andrew Newell
2015-3-13
Sorry, I realize now that I didn't really answer your question. The reason for the error is that you are not passing the values of Pg and P1 to f. One approach is to add them as input parameters. Or you could combine them as below:
R(n+1)=R(n)+h*f(t(n),(Pg(n)-P1(n))*R(n)) ;
The function is:
function f=f(~,x)
f=(x/152)-60;
Note the tilde. It's good practice to do this when an input variable (in this case t) is not used.
I ran this modified code and it produced a plot.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Function Creation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!