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

1 view (last 30 days)
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!

Accepted Answer

Matt J
Matt J on 20 May 2019
To get rid of global, implement as follows
a=1;
k=1;
T=1;
q=integral(@(t)a.*t.^k,0,T);
  2 Comments
Matt J
Matt J on 20 May 2019
Edited: Matt J on 20 May 2019
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

Sign in to comment.

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!