# MATLAB HELP! Simple scalar question and 'hold' graphing?

I am writing a programming code for euler method.

my code is

function [ y, t ] = Euler(t0,tf,y0,n )

%calculation of h using tf, t0 and n

h = (tf-t0)./n;

%intialization of x and y as column vectors

t = [t0 zeros(1,n)];

y = [y0 zeros(1,n)];

for i = 1:n

t(i+1)= t(i)+h;

y(i+1)= y(i)+h*fe(t(i),y(i));

end

plot(t,y)

end

I wanted to enter n = [ 2 4 8 16 ....]

and I keep getting an error

>> Euler(0,4,1,n)

Warning: Input arguments must be scalar.

> In Euler at 7

Warning: Input arguments must be scalar.

> In Euler at 8

In an assignment A(I) = B, the number of elements in B and I

must be the same.

Error in Euler (line 11)

t(i+1)= t(i)+h;

how can I also plot all of these different graphs with all the different n's?

Thank you

Update:

Sorry but in my command window I am inputing

n = [ 2 4 8 16 32 64]

Euler(0,4,1,n)

thank you!!

Relevance
• R G
Lv 5
8 years ago

u have a few mistakes....

function [ y, t ] = Euler(t0,tf,y0,n )

%calculation of h using tf, t0 and n

h = (tf-t0)./n;

%intialization of x and y as column vectors

%t = [t0 zeros(1,n)];

%y = [y0 zeros(1,n)];

t = [t0 zeros(1,size(n,2))];

y = [y0 zeros(1,size(n,2))];

%for i = 1:n

for i = 1:length(n)

%t(i+1)= t(i)+h;

%y(i+1)= y(i)+h(i)*fe(t(i),y(i));

t(i+1)= t(i)+h(i);

y(i+1)= y(i)+h(i)*fe(t(i),y(i)); %what is fe? it works with scalars?

end

plot(t,y)

end

%i think most of the errors are corrected