Why does my integral not work without the command "global"

1 次查看(过去 30 天)
function y=integrand1(t)
%UNTITLED3 Summary of this function goes here
% Detailed explanation goes here
global a k
y=a.*t.^k;
end
%Mainprogram
clc
clear all
global a k
%%
a=1;
k=1;
T=1;
q=integral(@integrand1,0,T);
%%
a=2;
k=1;
T=1;
b=integral(@integrand1,0,T);
%%
a=1;
k=2;
T=1;
c=integral(@integrand1,0,T);
%%
a=1;
k=1;
T=2;
d=integral(@integrand1,0,T);
%%
disp('answers for the integrals are: ')
disp([q b c d])
so my question is, how come the code won't work if i just remove the global command?
I have tried only crunching the first integral while getting rid of the Global command in both the function file and the main script but nop o.O
I'm curios as to what the global command actually does, the description is kinda hard to understand, maybe im super dumb.
Anyhow thanks on advance!

采纳的回答

Matt J
Matt J 2019-5-20
To get rid of global, implement as follows
a=1;
k=1;
T=1;
q=integral(@(t)a.*t.^k,0,T);
  2 个评论
Matt J
Matt J 2019-5-20
编辑:Matt J 2019-5-20
Or, you could do
a=1;
k=1;
T=1;
q=integral(@(t)integrand1(t,a,k) ,0,T);
with
function y=integrand1(t,a,k) %<---modified
y=a.*t.^k;
end

请先登录,再进行评论。

更多回答(0 个)

类别

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

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by