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 (최근 30일)
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
Alan Moses
Alan Moses 2021년 5월 11일
편집: Alan Moses 2021년 5월 11일
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

댓글을 달려면 로그인하십시오.

답변 (1개)

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by