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

1 Ansicht (letzte 30 Tage)
Aldin Hodzic
Aldin Hodzic am 20 Mai 2019
Bearbeitet: Matt J am 20 Mai 2019
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!

Akzeptierte Antwort

Matt J
Matt J am 20 Mai 2019
To get rid of global, implement as follows
a=1;
k=1;
T=1;
q=integral(@(t)a.*t.^k,0,T);
  2 Kommentare
Matt J
Matt J am 20 Mai 2019
Bearbeitet: Matt J am 20 Mai 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
Aldin Hodzic
Aldin Hodzic am 20 Mai 2019
Awesome! Thank you <3

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Produkte


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by