Sudal's Garage

MATLAB, pause를 이용한 움직이는 그래프, animation using pause 본문

Programming/MATLAB

MATLAB, pause를 이용한 움직이는 그래프, animation using pause

_Sudal 2019. 3. 3. 04:25

앞서 포스팅한 heatFTCS function을 이용해 시간에 따른 온도변화를 시각적으로 나타내보자


function animate1D 를 구현하자


% U: Matrix created by heatFTCS function % tf: Final time value used in heatFTCS function % L: Length L % speedx: run the animation x speed fast function animate1D(U,tf,L,speedx) [m,n] = size(U); X = linspace(0,L,m); % narrow down the number of column of U since its too slow having too % many data to draw I = 1:round(sqrt(n)/2):n; colormap jet set(gca,'YTick', []) % off y axis xlabel('Length') % x label xlim([0 L]); % x axis limit colorbar; % put colorbar caxis([min(min(U)) max(max(U))]) % set colorbar limit hold on; for i = I title(['Temperature distribution at t = ', num2str(i*tf/n),'s']) % title imagesc(X,[],U(:,i)') pause(tf/length(I)/speedx) % show n/tf frames in 1 second end title(['Temperature distribution at t = ', num2str(tf),'s']) % title imagesc(X,[],U(:,end)') end


Input:

U: heatFTCS 함수의 Output Matrix

tf: final time value

L: Length L

speedx: 배속설정. 2배속이면 2를 넣어준다


U Matrix 의 사이즈를 m과 n에 저장해준다.

X 는 x(displacement)를 나타내어 주기위한 U와 같은 길이의 vector

[m,n] = size(U); X = linspace(0,L,m);


U 의 Column은 같은 시간동안의 각 위치의 온도에 대한 데이터를 저장하고 있다.

모든 column의 데이터를 그래프화하면 시간이 너무 오래 걸림으로,  column의 수에 다라 적당히 그래프화 시킬 데이터 set을 정해준다 

I = 1:round(sqrt(n)/2):n;


Figure Property 를 설정해 주자

colormap jet set(gca,'YTick', []) % y축 설정

xlabel('Length') % x 축 제목

xlim([0 L]); % x 축 범위

colorbar; % 색표 추가

caxis([min(min(U)) max(max(U))]) % 색표 범위를 설정한다

hold on;


imagesc(x,y,C)는  이미지 위치를 지정한다.
X 벡터는 displacement 에 대한 데이터, [ ] 는 아무데이터를 저장하지 않고 있다. 1D-Heat에 대한 그래프를 보여주고 있기 때문.
U(:,i)' 는 i번째 displacement에 대응하는 Temperature를 저장하고 있다. U(:,i) 는 Column 벡터이므로, 끝에 '를 붙여 row 벡터로 바꾸어준다.

Pause(n) 은 n초 멈추는 함수이다.
Tf / length(I) / speedx 초 동안 쉬어주어, 적정한 시간동안 이미지가 바뀌게 설정해준다

for i = I
    title(['Temperature distribution at t = ', num2str(i*tf/n),'s']) % 제목
    imagesc(X,[],U(:,i)')
    pause(tf/length(I)/speedx) % n/tf 개의 프레임을 1초동안 보여준다
end

마지막 데이터 set, tf를 표한하기 위한 라인
title(['Temperature distribution at t = ', num2str(tf),'s']) % title imagesc(X,[],U(:,end)')

사실 I(end)에 마지막 행의 번호를 넣어주어도 된다!
이렇게,

I(end) = n;


아래 스크립트를 실행:

alpha = 0.1; L = 1; tf = 50;

F = @(x) zeros(size(x)); G0 = @(t) sin(1.2*t); GL = @(t) -2*sin(0.5*t);

h = 0.01; k = 0.0005;

U = heatFTCS(alpha,L,G0,GL,F,h,k,tf);


animate1D(U,tf,L,1)


result: