How to store an initial value in an array. x should start at 0 and y should start at 1. The step size is 0.25. I do not know how to store my initial x and y values in the array.

3 views (last 30 days)
clear;clc
syms x
syms y
f(x,y)= (1+2*x)*sqrt(y)
h = 0.25;
x_array = zeros(1,5); %array of x
y_array = zeros(1,5); %array of y
fprintf('Step 0: x = %6.2f, y = %6.2f\n', x, y);
for i=1:5
k1 = h*f(x,y);
k2 = h*f(x+h/2, y+k1/2);
k3 = h*f(x+h/2, y+k2/2);
k4 = h*f(x+h, y+k3);
y = y + (k1+2*k2+2*k3+k4)/6;
x = x + h;
fprintf('Step %d: x = %6.4f, y = %18.15f\n', i, x, y);
end
x_array(i+1) = x
y_array(i+1) = y
  1 Comment
Alan Moses
Alan Moses on 11 May 2021
Edited: Alan Moses on 11 May 2021
Do you wish to start your iterations with the initial values -> x=0 and y=1 ? You may try the following code:
clear;clc
syms x
syms y
f(x,y)= (1+2*x)*sqrt(y);
h = 0.25;
x0 = 0; %Initial value of x
y0 = 1; %Initial value of y
x_array = zeros(1,6); %array of x
y_array = zeros(1,6); %array of y
%Storing initial values in the array
x_array(1) = x0;
y_array(1) = y0;
fprintf('Step 0: x = %6.2f, y = %6.2f\n', x0, y0);
for i=1:5
k1 = h*f(x0,y0);
k2 = h*f(x0+h/2, y0+k1/2);
k3 = h*f(x0+h/2, y0+k2/2);
k4 = h*f(x0+h, y0+k3);
y0 = y0 + (k1+2*k2+2*k3+k4)/6;
x0 = x0 + h;
fprintf('Step %d: x = %6.4f, y = %18.15f\n', i, x0, y0);
x_array(i+1) = x0;
y_array(i+1) = y0;
end

Sign in to comment.

Answers (1)

Cris LaPierre
Cris LaPierre on 11 May 2021
I suggest Chs 4, 5 and 13 of MATLAB Onramp (vectors and arrays, indexing and modifying arrays, and for loops)

Products

Community Treasure Hunt

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

Start Hunting!