2차원 그래프 애니메이션 그리기
우선 애니매이션을 그릴 데이터를 선언한다. 간단한 예시로 sin 그래프를 그려보도록 하자.
theta = linspace(0,2*pi,100);
f = sin(theta);
애니메이션을 그리기 위해선 animatedline 함수를 사용해야 한다.
writer = animatedline;
figure(1)
xlim([0,2*pi]);
ylim([-1,1]);
for k = 1 : 1 : length(theta)
x = theta(k);
y = f(k);
addpoints(writer,x,y)
drawnow
end
for문을 반복하면서 animatedline에 값을 넣어주는 방식이다.
- 애니메이션 속도 조절
for문을 이해하고 있다면 속도 조절을 쉽게 할 수 있다. 1 : 1 : length(theta)로 된 부분을 1 : 2 : length(theta)로 바꿔주면 두 배로 빨라진다.
figure(1)
xlim([0,2*pi]);
ylim([-1,1]);
for k = 1 : 2 : length(theta)
x = theta(k);
y = f(k);
addpoints(writer,x,y)
drawnow
end
같은 방법으로 속도를 더 빠르게 할 수도 있고, 더 느리게 할 수 도 있다. 하지만 위와 같은 방법으로는 데이터에 손실이 발생할 수 있으므로 아래와 같이 해 주는것이 좋다.
figure(1)
xlim([0,2*pi]);
ylim([-1,1]);
for k = 1 : 2 : length(theta)
x = theta(k:k+1);
y = f(k:k+1);
addpoints(writer,x,y)
drawnow
end
for문을 이해한다면 다양하게 애니메이션을 만들 수 있므며, 그래프 뿐만 아니라 텍스트나 색갈 등의 애니메이션으로 응용할 수 있다. 3차원 그래프에서도 활용할 수 있다.
애니메이션 gif 저장
애니메이션 저장은 getframe과 imwrite를 통해 가능하다.
figure(1)
xlim([0,2*pi]);
ylim([-1,1]);
for k = 1 : 2 : length(theta)
x = theta(k:k+1);
y = f(k:k+1);
addpoints(writer,x,y)
drawnow
frame = getframe(1);
im = frame2im(frame);
[imind,cm] = rgb2ind(im,256);
if k==1
imwrite(imind,cm,'filename.gif','gif','Loopcount',inf);
else
imwrite(imind,cm,'filename.gif','gif','DelayTime',0.05,'WriteMode','append');
end
end
코드를 실행한 위치와 동일한 폴더에 저장된다.
애니메이션 파라미터
animatedline은 일반적인 그래프와 거의 유사한 인수를 받을 수 있다.
writer = animatedline('Color','w','MaximumNumPoints',100,'LineStyle','--','HandleVisibility','off');
색깔, 한번에 표시할 최대 좌표의 수 등등...
3차원 애니메이션
3차원에서 애니메이션 예제 이다.
theta = linspace(0,2*pi,100);
f = sin(theta);
h = cos(theta);
writer = animatedline;
figure(1)
view(3)
xlim([0,2*pi]);
ylim([-1,1]);
zlim([-1,1]);
grid on;
for k = 1 : 2 : length(theta)
x = theta(k:k+1);
y = f(k:k+1);
z = h(k:k+1);
addpoints(writer,x,y,z)
drawnow
end