Using variables between m-files
显示 更早的评论
I want to use an input dialog box for inputs in one m-file and use these inputs in another function...
Here is the first code:
x = inputdlg({'Rate', 'Population renewal', 'Death rate'}, 'Inputs')
b = str2double(x{1});
p = str2double(x{2});
l = 0.5;
d = 0.9;
m = str2double(x{3});
v = (b*p)*(1+(l*d));
c = m*(m+l);
R = /c;
if (R<1)
answer = msgbox(['Value = ' num2str(R) ' therefore there is no epidemic'],'Basic Reproduction number')
else
answer = msgbox(['Value = ' num2str(R) ' therefore there is an epidemic'],'Basic Reproduction number')
end
---------------------------------------------------------------------------------------------
I want to use the same inputs in another function and I am using the following code:
function msir = msirtry(t,y)
load('salRo.m','l','p','b','m','d');
d = 0.9;
c = 0.14;
a = 0.25;
r = 0.05;
msir(1) = p - m*y(1)- b*y(1)*y(2)*(1+(l*d)) + a*y(4);
msir(2) = b*y(1)*y(2)*(1+(l*d)) - (m + l)*y(2);
msir(3) = l*d*y(2) - (m + r)*y(3);
msir(4) = l*c*y(2) + r*y(3) - (m + a)*y(4);
msir = msir(:);
--------------------------------------------
and i am running this function using
yo = [20 5 5 10];
[t y] = ode45(@msirtry,[0 5],yo);
plot(t,y(:,1),t,y(:,2),t,y(:,3),t,y(:,4),'Linewidth',2.5)
legend('Susceptible','Infected Symptomatic','Infected Asymptomatic','Recovered')
--------------------------------------------------------------
I get the error - Number of columns on line 1 of ASCII file
C:\Users\Krishnaa\Documents\MATLAB\salRo.m
must be the same as previous lines.
if i manually put in the inputs instead of loading it, the codes work but I need to work all this out together... pls help...
采纳的回答
更多回答(2 个)
dpb
2013-9-23
0 个投票
You must either
a) make the variables GLOBAL so they're available in the other functions (HIGHLY not recommended), or
b) write an upper level script that calls the other functions in the proper, desired order that passes the needed inputs to the functions that need them (and then return the desired results for consumption/display).
You don't show what you did but it appears you tried to load an m-file instead of calling the function within it -- that, as you found out, doesn't work and isn't the way to use m-files/functions in Matlab.
Your last script should be turned into a function and passed the values you get from the dialog box or that few lines simply incorporated in the proper order in the script that calls the dialog box itself.
类别
在 帮助中心 和 File Exchange 中查找有关 Programming 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!