IrDe
IrDe

Reputation: 11

How to get GIF from figure

I made the code below. It produces the wanted graphs that I want to convert to a GIF, however this part isn't working. How can I adapt it so the GIF works?

function []=cyclotron()
t=0:0.01:27;
dt=[diff(t),eps];
figure, hold on
[x1,y1,z1] = sphere ;
xnew1=x1;ynew1=y1;znew1= -abs(z1);
s=surf(xnew1,ynew1,znew1);
s.FaceColor="yellow";
k=1;
[x,~,z] = sphere ; 
x0 =0.05*x;z0= 0.05*z-0.95; cenx=mean(mean(x0));cenz=mean(mean(z0));
r=arrayfun(@(x,z)imag(sqrt(0.95^2+0.05^2-2*(dot([cenx,cenz],[x,z])))),x0,z0); 
[ir,on,de] = sphere;
view(3)
f = getframe;
[im,map] = rgb2ind(f.cdata,256,'nodither');
im(1,1,1,2700) = 0;
for T = t
    xnew2=r*cos(10*T)*sin(-1.3*1.15^(-T)+1.3); 
    ynew2=r*sin(10*T)*sin(-1.3*1.15^(-T)+1.3); 
    znew2=r*cos(-1.3*1.15^(-T)+1.3);
    g=mean(mean(xnew2));
    ry=mean(mean(ynew2));
    s=mean(mean(znew2));
    ir2=0.05*ir-g;
    on2=0.05*on-ry;de2=0.05*de-s;
    h=surf(ir2,on2,de2);
    h.FaceColor="black";
    alpha 0.3;
    view(3)
    pause(dt(k));
    f = getframe;
    im(:,:,1,k) = rgb2ind(f.cdata,map,'nodither');
    delete(h)
    k=+1;
end
imwrite(im,map,'cyclotron.gif','DelayTime',0,'LoopCount',inf)
end

Upvotes: 1

Views: 79

Answers (1)

CAta.RAy
CAta.RAy

Reputation: 514

Use the imwrite function to create an animated GIF. An animated GIF contains a series of images all combined into one file. For this:

  1. Draw a series of plots

  2. Capture them as images

  3. Write them into a GIF file

Your current code will need to be modified to:

t=0:0.01:27;
dt=[diff(t),eps];
fig = figure; 
hold on
[x1,y1,z1] = sphere ;
xnew1=x1;ynew1=y1;znew1= -abs(z1);
s=surf(xnew1,ynew1,znew1);
s.FaceColor="yellow";
k=1;
[x,~,z] = sphere ; 
x0 =0.05*x;z0= 0.05*z-0.95; cenx=mean(mean(x0));cenz=mean(mean(z0));
r=arrayfun(@(x,z)imag(sqrt(0.95^2+0.05^2-2*(dot([cenx,cenz],[x,z])))),x0,z0); 
[ir,on,de] = sphere;
view(3)

% Capture the plot as an image 
frame = getframe(fig);
im = frame2im(frame);
[imind,cm] = rgb2ind(im,256);

% Write to the GIF File 
imwrite(imind,cm,'test1.gif','gif', 'Loopcount',inf); 


for T = t
    xnew2=r*cos(10*T)*sin(-1.3*1.15^(-T)+1.3); 
    ynew2=r*sin(10*T)*sin(-1.3*1.15^(-T)+1.3); 
    znew2=r*cos(-1.3*1.15^(-T)+1.3);
    g=mean(mean(xnew2));
    ry=mean(mean(ynew2));
    s=mean(mean(znew2));
    ir2=0.05*ir-g;
    on2=0.05*on-ry;de2=0.05*de-s;
    h=surf(ir2,on2,de2);
    h.FaceColor="black";
    alpha 0.3;
    view(3)
    pause(dt(k));
    % Capture the plot as an image 
    frame = getframe(fig);
    im = frame2im(frame);
    [imind,map] = rgb2ind(im,256);
    % Write to the GIF File 
    imwrite(imind,cm,filename,'gif','WriteMode','append'); 
    delete(h)
    k=+1;
end

Upvotes: 2

Related Questions