Essentially I have a loop as follows:
for i=0:0.5:n
dydx=-47*y+t^3;
y=y+dydx*h;
x=x+h;
end
At each iteration of the loop I would like to store the x and y values that I calculate in a vector, so that I can plot it later on. How would I do this? I tried to add y(i)=y and x(i)=x and I just get back an error warning.

Réponses (1)

Image Analyst
Image Analyst le 2 Mai 2020

0 votes

When you first enter the loop and get to this line:
dydx=-47*y+t^3;
can you tell us exactly what is y and t at that point?
Perhaps you want something like this but I have no idea:
numPoints = 20;
% Create initial sample data.
x = sort(rand(1, numPoints), 'ascend')
y = sort(rand(1, numPoints), 'ascend')
t = rand(1, numPoints);
h = 5; % Whatever.
for k = 1 : length(y)
dydx = -47*y(k) + t(k) ^3;
y(k) = y(k) + dydx * h;
x(k) = x(k) + h;
end
plot(x, y, 'b.-', 'LineWidth', 2, 'MarkerSize', 20);
grid on;

5 commentaires

Jordan Shook
Jordan Shook le 2 Mai 2020
At this point y is initially equal to 1 and for t I am integrating from 0 to 3 with step size of 0.5
Jordan Shook
Jordan Shook le 2 Mai 2020
The issue with this is that when I put all the varibles in the format of "y(k)" and "x(k)" I continue to come back with errors
Image Analyst
Image Analyst le 2 Mai 2020
I don't get any errors. And I can't run your code since you only gave a small snippet which gives an entirely different error than what you're asking about. How can we run your code and see the error you have? Hint: read this link.
Jordan Shook
Jordan Shook le 2 Mai 2020
Here is my whole code:
Essentially I am trying to use Eulers method to get t and y values that I will plot on an x,y graph. I have changed the numbers because this is a school assignement, and although I am not asking for my code to be written, simply just how to store varibles, I would like to make sure that the assignment does not match.
%% Problem 3
%part a euler
t0=1;
tf=5;
y=1;
h=0.5;
n=(tf-t0)/h;
for i=0:0.3:n
dydt=-7*y+t^3;
y=y+dydt*h;
t=t+h;
end
Image Analyst
Image Analyst le 2 Mai 2020
OK, well then you need to index y and y if you want them to change. Use y(i) = ... and t(i) = .....

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by