MATLAB function printing extra matrix?

  • MATLAB
  • Thread starter Gengar
  • Start date
  • #1
13
0

Main Question or Discussion Point

I'm a newbie to all things programming, and have to write a program implementing the Euler method to approximate an ODE.

Anyways, the program works but when I use the function I wrote I get an extra matrix of zeroes above the desired output, which I don't understand as I have suppressed the output of the zero matrix with a semi-colon - the matrix is Eulerpoints. Here's the source code:


function [Eulerpoints] = Eulermethod(x0,y0,xn,steps)
%EULERMETHOD - this function will approximate y by the Euler method.
% EULERMETHOD(x0,y0,xn,steps) will return a list of points that
% approximate y in the interval [x0,xn] given our initial co-ordinate
% (x0,y0) and the number of steps.

Eulerpoints=zeros(steps+1,2);
start = 2;
finish = steps+1;
h=(xn-x0)/steps;
Eulerpoints(1,1) = x0, Eulerpoints(1,2) = y0;
fprintf(' n xn Yn\n 0 %2g %2g\n',x0,y0)

for I= start:finish
Eulerpoints(I,1) = x0 +h*(I-1);
Eulerpoints(I,2) = Eulerpoints(I-1,2) + h*(-2*Eulerpoints(I-1,2) - 0.25*Eulerpoints(I-1,1)*Eulerpoints(I-1,1) + 0.125); %% This line contains the ODE, which can be adjusted for a different equation.
fprintf('%3g %4g %6g\n',I-1,Eulerpoints(I,1),Eulerpoints(I,2))
end
%
end
 

Answers and Replies

  • #2
12
0
The x0 in Line 11 needs to have a semi-colon after it. This will then return the Eulerpoints matrix as a variable and the [n xn yn] print out that you call for, but you will no longer have the output you were concerned with.

Here is the fixed code (using the CODE wrap that we have here on PF):

Code:
function [Eulerpoints] = Eulermethod(x0,y0,xn,steps)
%EULERMETHOD - this function will approximate y by the Euler method.
% EULERMETHOD(x0,y0,xn,steps) will return a list of points that
% approximate y in the interval [x0,xn] given our initial co-ordinate
% (x0,y0) and the number of steps.

Eulerpoints=zeros(steps+1,2);
start = 2;
finish = steps+1;
h=(xn-x0)/steps;
Eulerpoints(1,1) = x0; Eulerpoints(1,2) = y0;
fprintf(' n xn Yn\n 0 %2g %2g\n',x0,y0)

for I= start:finish
Eulerpoints(I,1) = x0 +h*(I-1);
Eulerpoints(I,2) = Eulerpoints(I-1,2) + h*(-2*Eulerpoints(I-1,2) - 0.25*Eulerpoints(I-1,1)*Eulerpoints(I-1,1) + 0.125); %% This line contains the ODE, which can be adjusted for a different equation.
fprintf('%3g %4g %6g\n',I-1,Eulerpoints(I,1),Eulerpoints(I,2))
end
%
end
Hope this helps.

Ben
 
  • #3
13
0
Ah thanks, yeh that's been bugging me (geddit?) for ages.
Cheers
 

Related Threads on MATLAB function printing extra matrix?

Replies
1
Views
4K
Replies
4
Views
2K
  • Last Post
Replies
6
Views
467
  • Last Post
Replies
13
Views
2K
Replies
5
Views
43K
Replies
0
Views
8K
Replies
1
Views
2K
  • Last Post
Replies
2
Views
3K
  • Last Post
Replies
1
Views
1K
Replies
0
Views
4K
Top