Storing x and y values
Show older comments
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.
Answers (1)
Image Analyst
on 2 May 2020
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 Comments
Jordan Shook
on 2 May 2020
Jordan Shook
on 2 May 2020
Image Analyst
on 2 May 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
on 2 May 2020
Image Analyst
on 2 May 2020
OK, well then you need to index y and y if you want them to change. Use y(i) = ... and t(i) = .....
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!