How do I store values from a for loop

조회 수: 1 (최근 30일)
Roger Burtus
Roger Burtus 2018년 10월 31일
답변: Star Strider 2018년 10월 31일
This is euler's method. I need to plot x0 against y0 without doing it inside the forloop, as it causes performance issues later on. I thought that maybe I could store all individual values of x0 and y0 from the forloop inside two separate vectors and then perform the plot, so that I don't need to plot for every iteration of the forloop. What should I write to store it in vectors? The next problem: This is a function file, so if I store the data in two vectors, how do I recall the data in order to perform a plot, when I am outside the function file?
function euler = eul(n,h)
y0 = 0;
x0 = 0;
%%dy is a separate function located somewhere else
for t = 1:n
x1 = x0 + h;
y1 = y0 + h * dy(y0);
euler = y1;
%%updating values x0 and y0 in preparation for next loop
x0 = x1;
y0 = y1;
%%This is my current abomination of an attempt to plot.
plot(x0,y0,'x')
hold on
end
end
  댓글 수: 1
madhan ravi
madhan ravi 2018년 10월 31일
Upload all the necessary information instead of giving information but by bit , saves time!!

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

채택된 답변

Star Strider
Star Strider 2018년 10월 31일
‘What should I write to store it in vectors?’
I would create ‘x0v’ and ‘y0v’ (for example) to store them:
function [euler,x0v,y0v] = eul(n,h)
y0 = 0;
x0 = 0;
x0v = zeros(1,n); % Preallocate
y0v = zeros(1,n); % Preallocate
%%dy is a separate function located somewhere else
for t = 1:n
x1 = x0 + h;
y1 = y0 + h * dy(y0);
euler = y1;
%%updating values x0 and y0 in preparation for next loop
x0 = x1;
y0 = y1;
x0v(t) = x0;
y0v(t) = y0;
%%This is my current abomination of an attempt to plot.
plot(x0v, y0v, 'x')
hold on
end
end
‘... how do I recall the data in order to perform a plot ...’
Add them as outputs, as I did here. The rest of your code is unchanged.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by