分享一个Matlab老祖宗520代码,有需要可以一用。
一、静态心形
[if !vml]
[endif]
代码如下:
%静态爱心clear allclcf=@(x,y,z)(x.^2+ (9./4).*y.^2+ z.^2-1).^3- x.^2.*z.^3- (9./80).*y.^2.*z.^3;[x,y,z]=meshgrid(linspace(-3,3));val=f(x,y,z);[p,v]=isosurface(x,y,z,val,0);patch('faces',p,'vertices',v,'facevertexcdata',jet(size(v,1)),'facecolor','w','edgecolor','flat');view(3);gridon;axis equal;
[if !supportLineBreakNewLine]
[endif]
二、动态心形
[if !vml]
[endif]
代码如下:
%动态爱心clear; clc; close all; %NOTICE: Your MATLAB version should be at least R2019a !
% --------------------------- functions -------------------------------f = @(x,y, z)(x.^2+2.25*y.^2+ z.^2-1).^3- ... x.^2.* z.^3-0.1125*y.^2.*z.^3;g = @(x, y, z)(sqrt(x.^2+y.^2)-2.5).^2+ z.^2-0.4^2;
% -------------------------- generate data ----------------------------t =linspace(-5,5);
[x1, y1, z1] = meshgrid(t);[x2, y2, z2] = meshgrid(t);
val1 = f(x1, y1, z1);val2 = g(x2, y2, z2);
[p1, v1] = isosurface(x1, y1, z1, val1,0);[p2, v2] =isosurface(x2, y2, z2, val2,0);
% --------------------------- basic plot------------------------------figure()subplot(1,1,1)
h = patch('faces',p1,'vertices',v1,'facevertexcdata',jet(size(v1,1)),... 'facecolor','w','edgecolor','flat');holdon;patch('faces',p2,'vertices',v2,'facevertexcdata',jet(size(v2,1)),... 'facecolor','w','edgecolor','flat');gridon; axis equal; axis([-3,3,-3,3,-1.5,1.5]);view(3)title(["
程式解说",... "给个关注呗!"],'Interpreter','latex','position',[3.3,4])warning('off');%大声说出来!% 大声说出来!T = suptitle("$I\ Love\ U\ !$"); %大声说出来!% 大声说出来!set(T,'Interpreter','latex','FontSize',24)
% -------------------------- generate gif -----------------------------pic_num=1;fori=1:20 v1 =0.98* v1; set(h,'vertices', v1); drawnow; F = getframe(gcf); I = frame2im(F); [I,map]=rgb2ind(I,256); ifpic_num ==1 imwrite(I,map,'BeatingHeart.gif','gif','Loopcount',inf,'DelayTime',0.05); else imwrite(I,map,'BeatingHeart.gif','gif','WriteMode','append','DelayTime',0.05); end pic_num = pic_num +1;endfori =1:20 v1 = v1 /0.98; set(h,'vertices', v1); drawnow; F = getframe(gcf); I = frame2im(F); [I,map]= rgb2ind(I,256); imwrite(I,map,'BeatingHeart.gif','gif','WriteMode','append','DelayTime',0.05); pic_num = pic_num +1;end
% -----------------------------dynamic-------------------------------whiletrue fori =1:20 v1=0.98* v1; set(h,'vertices', v1); drawnow; end fori =1:20 v1= v1 /0.98; set(h,'vertices', v1); drawnow; endend
(获取更多知识,前往wx 公z号 程式解说)
原文来自https://mp.weixin.qq.com/s/o3uTht1I-QsHY76TjNQMsQ