matlab central discussions -凯发k8网页登录

pull up a chair!

discussions is your place to get to know your peers, tackle the bigger challenges together, and have fun along the way.

  • want to see the latest updates? follow the !
  • looking for techniques improve your matlab or simulink skills? has you covered!
  • sharing the perfect math joke, pun, or meme? look no further than !
  • think there's a channel we need? tell us more in



posted 2024-2-17,8:38

2 x 2 행렬의 행렬식은
  • 행렬의 두 row 벡터로 정의되는 평행사변형의 면적입니다.
  • 물론 두 column 벡터로 정의되는 평행사변형의 면적이기도 합니다.
  • 좀 더 정확히는 signed area입니다. 면적이 음수가 될 수도 있다는 뜻이죠.
  • 행렬의 두 행(또는 두 열)을 맞바꾸면 행렬식의 부호도 바뀌고 면적의 부호도 바뀌어야합니다.
일반적으로 n x n 행렬의 행렬식은
  • 각 row 벡터(또는 각 column 벡터)로 정의되는 n차원 공간의 평행면체(?)의 signed area입니다.
  • 제대로 이해하려면 대수학의 개념을 많이 가지고 와야 하는데 자세한 설명은 생략합니다.(=저도 모른다는 뜻)
  • 더 자세히 알고 싶으시면 의 '넓이 이야기' 편을 추천합니다.
  • 수학적인 정의를 알고 싶으시면 를 보시면 됩니다.
  • 이렇게 생겼습니다. 좀 무섭습니다.
아래 코드는...
  • 2 x 2 행렬에 대해서 이것을 수식 없이 그림만으로 증명하는 과정입니다.
  • gif 생성에는 를 사용했습니다. (gif 만들기엔 이게 킹왕짱인듯)
determinant of 2 x 2 matrix is...
  • an area of a parallelogram defined by two row vectors.
  • of course, same one defined by two column vectors.
  • precisely, a signed area, which means area can be negative.
  • if two rows (or columns) are swapped, both the sign of determinant and area change.
more generally, determinant of n x n matrix is...
  • signed area of parallelepiped defined by rows (or columns) of the matrix in n-dim space.
  • for a full understanding, a lot of concepts from abstract algebra should be brought, which i will not write here. (cuz i don't know them.)
  • for a mathematical definition of determinant, visit .
  • a little scary, isn't it?
the code below is...
  • a process to prove the equality of the determinant of 2 x 2 matrix and the area of parallelogram.
  • is used to generate gif animation (which is, to me, the easiest way to make gif).
% 두 점 (a, b), (c, d)의 좌표
a = 4;
b = 1;
c = 1;
d = 3;
% patch 색 pre-define
lightgreen = [144, 238, 144]/255;
lightblue = [169, 190, 228]/255;
lightorange = [247, 195, 160]/255;
% animation params.
anim_nsteps = 30;
% create window
figure('windowstyle','docked')
ax = axes;
ax.xaxislocation = 'origin';
ax.yaxislocation = 'origin';
ax.xtick = [];
ax.ytick = [];
hold on
ax.xlim = [-.4, a c 1];
ax.ylim = [-.4, b d 1];
% create ad-bc patch
area = patch([0, a, a c, c], [0, b, b d, d], lightgreen);
p_ab = plot(a, b, 'ko', 'markerfacecolor', 'k');
p_cd = plot(c, d, 'ko', 'markerfacecolor', 'k');
p_ab.userdata = text(a 0.1, b, '(a, b)', 'fontsize',16);
p_cd.userdata = text(c 0.1, d-0.2, '(c, d)', 'fontsize',16);
area.userdata = text((a c)/2-0.5, (b d)/2, 'ad-bc', 'fontsize', 18);
pause
%% is this really ad-bc?
area.userdata.string = 'ad-bc...?';
pause
%% fade out ad-bc
fadeinout(area, 0)
area.userdata.visible = 'off';
pause
%% fade in ad block
rect_ad = patch([0, a, a, 0], [0, 0, d, d], lightblue, 'edgealpha', 0, 'facealpha', 0);
uistack(rect_ad, 'bottom');
fadeinout(rect_ad, 1, t_pause=0.003)
draw_gridline(rect_ad, ["23", "34"])
rect_ad.userdata = text(mean(rect_ad.xdata), mean(rect_ad.ydata), 'ad', 'fontsize', 20, 'horizontalalignment', 'center');
pause
%% fade-in bc block
rect_bc = patch([0, c, c, 0], [0, 0, b, b], lightorange, 'edgealpha', 0, 'facealpha', 0);
fadeinout(rect_bc, 1, t_pause=0.0035)
draw_gridline(rect_bc, ["23", "34"])
rect_bc.userdata = text(b/2, c/2, 'bc', 'fontsize', 20, 'horizontalalignment', 'center');
pause
%% slide ad block
patch_slide(rect_ad, ...
[0, 0, 0, 0], [0, b, b, 0], t_pause=0.004)
draw_gridline(rect_ad, ["12", "34"])
pause
%% slide ad block
patch_slide(rect_ad, ...
[0, 0, d/(d/c-b/a), d/(d/c-b/a)],...
[0, 0, b/a*d/(d/c-b/a), b/a*d/(d/c-b/a)], t_pause=0.004)
draw_gridline(rect_ad, ["14", "23"])
pause
%% slide bc block
uistack(p_cd, 'top')
patch_slide(rect_bc, ...
[0, 0, 0, 0], [d, d, d, d], t_pause=0.004)
draw_gridline(rect_bc, "34")
pause
%% slide bc block
patch_slide(rect_bc, ...
[0, 0, a, a], [0, 0, 0, 0], t_pause=0.004)
draw_gridline(rect_bc, "23")
pause
%% slide bc block
patch_slide(rect_bc, ...
[d/(d/c-b/a), 0, 0, d/(d/c-b/a)], ...
[b/a*d/(d/c-b/a), 0, 0, b/a*d/(d/c-b/a)], t_pause=0.004)
pause
%% finalize: fade out ad, bc, and fade in ad-bc
rect_ad.userdata.visible = 'off';
rect_bc.userdata.visible = 'off';
fadeinout([rect_ad, rect_bc, area], [0, 0, 1])
area.userdata.string = 'ad-bc';
area.userdata.visible = 'on';
%% functions
function fadeinout(objs, inout, options)
arguments
objs
inout % 1이면 fade-in, 0이면 fade-out
options.anim_nsteps = 30
options.t_pause = 0.003
end
for alpha = linspace(0, 1, options.anim_nsteps)
for i = 1:length(objs)
switch objs(i).type
case 'patch'
objs(i).facealpha = (inout(i)==1)*alpha (inout(i)==0)*(1-alpha);
objs(i).edgealpha = (inout(i)==1)*alpha (inout(i)==0)*(1-alpha);
case 'constantline'
objs(i).alpha = (inout(i)==1)*alpha (inout(i)==0)*(1-alpha);
end
pause(options.t_pause)
end
end
end
function patch_slide(obj, x_dist, y_dist, options)
arguments
obj
x_dist
y_dist
options.anim_nsteps = 30
options.t_pause = 0.003
end
dx = x_dist/options.anim_nsteps;
dy = y_dist/options.anim_nsteps;
for i=1:options.anim_nsteps
obj.xdata = obj.xdata dx(:);
obj.ydata = obj.ydata dy(:);
obj.userdata.position(1) = mean(obj.xdata);
obj.userdata.position(2) = mean(obj.ydata);
pause(options.t_pause)
end
end
function draw_gridline(patch, where)
ax = patch.parent;
for i=1:length(where)
v1 = str2double(where{i}(1));
v2 = str2double(where{i}(2));
x1 = patch.xdata(v1);
x2 = patch.xdata(v2);
y1 = patch.ydata(v1);
y2 = patch.ydata(v2);
if x1==x2
xline(x1, 'k--')
else
fplot(@(x) (y2-y1)/(x2-x1)*(x-x1) y1, [ax.xlim(1), ax.xlim(2)], 'k--')
end
end
end

    posted 2024-2-16,12:47

    i think that had quite some inspiring entries. my work largely deals with digital elevation models (dems). hence i really liked the random renderings of landscapes, in particular written by which inspired me to adopt the code and apply to the example data that comes with . the results and code are shown .

    posted 2024-2-16,12:07

    on valentine's day, the mathworks linkedin channel this animated gif
    and immeditaely everyone wanted the code! it turns out that this is the result of my remix of 's entry on the matlab flipbook mini hack.
    i pointed people to the flipbook entry but, of course, that just gave the code to render a single frame and people wanted the full code to render the animated gif. that way, they could make personalised versions
    i just published a blog post that gives the code used by the team behind the mini hack to produce the animated .gifs
    thanks again to for a great entry that seems like it will live for a long time :)

    posted 2024-2-15,23:19

    if you've dabbled in "procedural generation," (algorithmically generating natural features), you may have come across the problem of sphere texturing. how to seamlessly texture a sphere is not immediately obvious. watch what happens, for example, if you try adding power law noise to an evenly sampled grid of spherical angle coordinates (i.e. a "uv sphere" in blender-speak):
    % example: how [not] to texture a sphere:
    rng(2, 'twister'); % make what i have here repeatable for you
    % make our radial noise, mapped onto an equal spaced longitude and latitude
    % grid.
    n = 51;
    b = linspace(-1, 1, n).^2;
    r = abs(ifft2(exp(6i*rand(n))./(b' b 1e-5))); % power law noise
    r = rescale(r, 0, 1) 5;
    [lon, lat] = meshgrid(linspace(0, 2*pi, n), linspace(-pi/2, pi/2, n));
    [x2, y2, z2] = sph2cart(lon, lat, r);
    r2d = @(x)x*180/pi;
    % radial surface texture
    subplot(1, 3, 1);
    imagesc(r, 'xdata', r2d(lon(1,:)), 'ydata', r2d(lat(:, 1)));
    xlabel('longitude (deg)');
    ylabel('latitude (deg)');
    title('texture (radial variation)');
    % view from z axis
    subplot(1, 3, 2);
    surf(x2, y2, z2, r);
    axis equal
    view([0, 90]);
    title('top view');
    % side view
    subplot(1, 3, 3);
    surf(x2, y2, z2, r);
    axis equal
    view([-90, 0]);
    title('side view');
    the created surface shows "pinching" at the poles due to different radial values mapping to the same location. furthermore, the noise statistics change based on the density of the sampling on the surface.
    how can this be avoided? one standard method is to create a textured volume and sample the volume at points on a sphere. code for doing this is quite simple:
    rng default% make our noise realization repeatable
    % create our 3d power-law noise
    n = 201;
    b = linspace(-1, 1, n);
    [x3, y3, z3] = meshgrid(b, b, b);
    b3 = x3.^2 y3.^2 z3.^2;
    r = abs(ifftn(ifftshift(exp(6i*randn(size(b3)))./(b3.^1.2 1e-6))));
    % modify it - make it more interesting
    r = rescale(r);
    r = r./(abs(r - 0.5) .1);
    % sample on a sphere
    [x, y, z] = sphere(500);
    % plot
    ir = interp3(x3, y3, z3, r, x, y, z, 'linear', 0);
    surf(x, y, z, ir);
    shading flat
    axis equal off
    set(gcf, 'color', 'k');
    colormap(gray);
    the result of evaluating this code is a seamless, textured sphere with no discontinuities at the poles or variation in the spatial statistics of the noise texture:
    but what if you want to smooth it or perform some other local texture modification? smoothing the volume and resampling is not equivalent to smoothing the surficial features shown on the map above.
    a more flexible alternative is to treat the samples on the sphere surface as a set of interconnected nodes that are influenced by adjacent values. using this approach we can start by defining the set of nodes on a sphere surface. these can be sampled almost arbitrarily, though the noise statistics will vary depending on the sampling strategy.
    one noise realisation i find attractive can be had by randomly sampling a sphere. normalizing a point in n-dimensional space by its 2-norm projects it to the surface of an n-dimensional unit sphere, so randomly sampling a sphere can be done very easily using randn() and vecnorm():
    n = 5e3; % number of nodes on our sphere
    g=randn(3,n); % random 3d points around origin
    p=g./vecnorm(g); % projected to unit sphere
    the next step is to find each point's "neighbors." the first step is to find the convex hull. since each point is on the sphere, the convex hull will include each point as a vertex in the triangulation:
    k=convhull(p');
    in the above, k is an n x 3 set of indices where each row represents a unique triangle formed by a triplicate of points on the sphere surface. the vertices of the full set of triangles containing a point describe the list of neighbors to that point.
    what we want now is a large, sparse symmetric matrix where the indices of the columns & rows represent the indices of the points on the sphere and the nth row (and/or column) contains non-zero entries at the indices corresponding to the neighbors of the nth point.
    how to do this? you could set up a tiresome nested for-loop searching for all rows (triangles) in k that contain some index n, or you could directly index via:
    c=@(x)sparse(k(:,x)*[1,1,1],k,1,n,n);
    t=c(1)|c(2)|c(3);
    the result is the desired sparse connectivity matrix: a matrix with non-zero entries defining neighboring points.
    so how do we create a textured sphere with this connectivity matrix? we will use it to form a set of equations that, when combined with the concept of "regularization," will allow us to determine the properties of the randomness on the surface. our regularizer will penalize the difference of the radial distance of a point and the average of its neighbors. to do this we replace the main diagonal with the negative of the sum of the off-diagonal components so that the rows and columns are zero-mean. this can be done via:
    w=spdiags(-sum(t,2) 1,0,double(t));
    now we invoke a bit of linear algebra. pretend x is an n-length vector representing the radial distance of each point on our sphere with the noise realization we desire. y will be an n-length vector of "observations" we are going to generate randomly, in this case using a uniform distribution (because it has a bias and we want a non-zero average radius, but you can play around with different distributions than uniform to get different effects):
    y=rand(n,1);
    and a is going to be our "transformation" matrix mapping x to our noisy observations:
    ax = y
    in this case both x and y are n length vectors and a is just the identity matrix:
    a = speye(n);
    y, however, doesn't create the noise realization we want. so in the equation above, when solving for x we are going to introduce a regularizer which is going to penalize unwanted behavior of x by some amount. that behavior is defined by the point-neighbor radial differences represented in matrix w. our estimate of x can then be found using one of my favorite matlab assets, the "\" operator:
    smoothness = 10; % smoothness penalty: higher is smoother
    x = (a smoothness*w'*w)\y; % solving for radii
    the vector x now contains the radii with the specified noise realization for the sphere which can be created simply by multiplying x by p and plotting using trisurf:
    p2 = p.*x';
    trisurf(k,p2(1,:),p2(2,:),p2(3,:),'facec', 'w', 'edgec', 'none','ambients',0,'diffuses',0.6,'speculars',1);
    light;
    set(gca, 'color', 'k');
    axis equal
    the following images show what happens as you change the smoothness parameter using values [.1, 1, 10, 100] (left to right):
    now you know a couple ways to make a textured sphere: that's the starting point for having a lot of fun with basic procedural planet, moon, or astroid generation! here's some examples of things you can create based on these general ideas:

    posted 2024-2-15,22:46

    the matlab command window isn't just for commands and outputs—it can also host interactive hyperlinks. these can serve as powerful shortcuts, enhancing the feedback you provide during code execution. here are some hyperlinks i frequently use in fprintf statements, warnings, or error messages.
    1. open a website.
    msg = "could not download data from website.";
    url = "https://blogs.mathworks.com/graphics-and-apps/";
    hypertext = "go to website"
    fprintf(1,'%s \n',msg,url,hypertext);
    could not download data from website.
    2. open a folder in file explorer (windows)
    msg = "file saved to current directory.";
    directory = cd();
    hypertext = "[open directory]";
    fprintf(1,'%s \n',msg,directory,hypertext)
    file saved to current directory.
    3. open a document (windows)
    msg = "created database.csv.";
    filepath = fullfile(cd,'database.csv');
    hypertext = "[open file]";
    fprintf(1,'%s \n',msg,filepath,hypertext)
    created database.csv.
    4. open an m-file and go to a specific line
    msg = 'go to';
    file = 'streamline.m';
    line = 51;
    fprintf(1,'%s ', msg, file, line, file, line);
    go to
    5. display more text
    msg = 'incomplete data detected.';
    extendedinfo = '\tfilename: m32c4r28\n\tdate: 12/20/2014\n\telectrode: (3,7)\n\tdepth: ???\n';
    hypertext = '[click for more info]';
    warning('%s ', msg,extendedinfo,hypertext);
    warning: incomplete data detected.
    • filename: m32c4r28
    • date: 12/20/2014
    • electrode: (3,7)
    • depth: ???
    6. run a function
    see
    similarly, you can also add hyperlinks in figures and apps
    • (r2021a)

    posted 2024-2-14,15:39

    see in our community contest area. (author: )
    and what do you do for valentine's day?

      posted 2024-2-10,13:59

      which technical support should i contact/ask for the published simscape example?

      posted 2024-2-10,3:46

      happy year of the dragon.

        image analyst
        image analyst
        posted 2024-2-10,2:15

        to enlarge an array with more rows and/or columns, you can set the lower right index to zero. this will pad the matrix with zeros.
        m = rand(2, 3) % initial matrix is 2 rows by 3 columns
        mcopy = m;
        % now make it 2 rows by 5 columns
        m(2, 5) = 0
        m = mcopy; % go back to original matrix.
        % now make it 3 rows by 3 columns
        m(3, 3) = 0
        m = mcopy; % go back to original matrix.
        % now make it 3 rows by 7 columns
        m(3, 7) = 0

        posted 2024-2-8,18:24

        i was looking into the possibility of making a spin-to-win prize wheel in matlab. i was looking around, and if someone has made one before they haven't shared. a labeled colored spinning wheel, that would slow down and stop (or i would take just stopping) at a random spot each time. i would love any tips or links to helpful resources!

        posted 2024-2-7,22:13

        many of the examples in the matlab documentation are extremely high quality articles, often worthy of attention in their own right. time to start celebrating them! today's is how to increase image resolution using deep learning

        posted 2024-2-7,19:14

        can you see them?

          posted 2024-2-7,0:51

          i have been procrastinating on schoolwork by looking at all the amazing designs created in the last matlab flipbook mini hack! they are just amazing. the voting is over but what are y'all's personal favorites? mine is the , it is for sure a creation i plan to share with others in the future!

          posted 2024-2-6,17:12

          it is easy to obtain sankey plot like that using my tool:

            posted 2024-2-6,16:58

            code is here
            you can also see the animated version of the competition here

              posted 2024-2-6,11:38

              struct is an easy way to combine different types of variants. but now matlab supports classes well, and i think class is always a better alternative than struct. i can't find a single scenario that struct is necessary. there are many shortcomings using structs in a project, e.g. uncontrollable field names, unexamined values, etc. what's your opinion?

              posted 2024-2-5,3:05

              function dragon24
              % 凯发官网入口首页 copyright (c) 2024, zhaoxu liu / slandarer
              basev=[ -.016,.822; -.074,.809; -.114,.781; -.147,.738; -.149,.687; -.150,.630;
              -.157,.554; -.166,.482; -.176,.425; -.208,.368; -.237,.298; -.284,.216;
              -.317,.143; -.338,.091; -.362,.037;-.382,-.006;-.420,-.051;-.460,-.084;
              -.477,-.110;-.430,-.103;-.387,-.084;-.352,-.065;-.317,-.060;-.300,-.082;
              -.331,-.139;-.359,-.201;-.385,-.262;-.415,-.342;-.451,-.418;-.494,-.510;
              -.533,-.599;-.569,-.675;-.607,-.753;-.647,-.829;-.689,-.932;-.699,-.988;
              -.639,-.905;-.581,-.809;-.534,-.717;-.489,-.642;-.442,-.543;-.393,-.447;
              -.339,-.362;-.295,-.296;-.251,-.251;-.206,-.241;-.183,-.281;-.175,-.350;
              -.156,-.434;-.136,-.521;-.128,-.594;-.103,-.677;-.083,-.739;-.067,-.813;-.039,-.852];
              % 基础比例、上色方式数据
              basev=[0,.82;basev;basev(end:-1:1,:).*[-1,1];0,.82];
              basev=basev-mean(basev,1);
              basef=1:size(basev,1);
              basey=basev(:,2);
              basey=(basey-min(basey))./(max(basey)-min(basey));
              n=30;
              baser=sin(linspace(pi/4,5*pi/6,n))./1.2;
              baser=[baser',baser'];baser(1,:)=[1,1];
              baser(5,:)=[2,.6];
              baser(10,:)=[3.7,.4];
              baser(15,:)=[1.8,.6];
              baset=[zeros(n,1),ones(n,1)];
              basem=zeros(n,2);
              based=basem;
              ratiot=@(mat,t)mat*[cos(t),sin(t);-sin(t),cos(t)];
              % 配色数据
              clist=[211,56,32;56,105,166;253,209,95]./255;
              % clist=bone(4);clist=clist(2:4,:);
              % clist=flipud(bone(3));
              % clist=lines(3);
              % clist=colorcube(3);
              % clist=rand(3)
              basec1=clist(2,:) basey.*(clist(1,:)-clist(2,:));
              basec2=clist(3,:) basey.*(clist(1,:)-clist(3,:));
              % 构建图窗
              fig=figure('units','normalized','position',[.1,.1,.5,.8],...
              'userdata',[98,121,32,115,108,97,110,100,97,114,101,114]);
              axes('parent',fig,'nextplot','add','color',[0,0,0],...
              'dataaspectratio',[1,1,1],'xlim',[-6,6],'ylim',[-6,6],'position',[0,0,1,1]);
              % 构造龙每个部分句柄
              dragonhdl(1)=patch('faces',basef,'vertices',basev,'facevertexcdata',basec1,'facecolor','interp','edgecolor','none','facealpha',.95);disp(char(fig.userdata))
              for i=2:n
              dragonhdl(i)=patch('faces',basef,'vertices',basev.*baser(i,:)-[0,i./2.5-.3],'facevertexcdata',basec2,'facecolor','interp','edgecolor','none','facealpha',.7);
              end
              set(dragonhdl(5),'facevertexcdata',basec1,'facealpha',.7)
              set(dragonhdl(10),'facevertexcdata',basec1,'facealpha',.7)
              set(dragonhdl(15),'facevertexcdata',basec1,'facealpha',.7)
              for i=n:-1:1,uistack(dragonhdl(i),'top');end
              for i=1:n
              basem(i,:)=mean(get(dragonhdl(i),'vertices'),1);
              end
              based=diff(basem(:,2));pos=[0,2];
              % 主循环及旋转、运动计算
              set(gcf,'windowbuttonmotionfcn',@dragonfcn)
              fps=8;
              game=timer('executionmode', 'fixedrate', 'period',1/fps, 'timerfcn', @dragongame);
              start(game)
              % 凯发官网入口首页 copyright (c) 2023, zhaoxu liu / slandarer
              set(gcf,'tag','co','closerequestfcn',@clo);
              function clo(~,~)
              stop(game);delete(findobj('tag','co'));clf;close
              end
              function dragongame(~,~)
              dir=pos-basem(1,:);
              dir=dir./norm(dir);
              baset=(baset(1:end,:) [dir;baset(1:end-1,:)])./2;
              baset=baset./(vecnorm(baset')');
              theta=atan2(baset(:,2),baset(:,1))-pi/2;
              basem(1,:)=basem(1,:) (pos-basem(1,:))./30;
              basem(2:end,:)=basem(1,:) [cumsum(based.*baset(2:end,1)),cumsum(based.*baset(2:end,2))];
              for ii=1:n
              set(dragonhdl(ii),'vertices',ratiot(basev.*baser(ii,:),theta(ii)) basem(ii,:))
              end
              end
              function dragonfcn(~,~)
              xy=get(gca,'currentpoint');
              x=xy(1,1);y=xy(1,2);
              pos=[x,y];
              pos(pos>6)=6;
              pos(pos<-6)=6;
              end
              end

                posted 2024-2-5,2:56

                there will be a warning when we try to solve equations with piecewise:
                syms x y
                a = x y;
                b = 1.*(x > 0) 2.*(x <= 0);
                eqns = [a b*x == 1, a - b == 2];
                s = solve(eqns, [x y]);
                % 错误使用 mupadengine/feval_internal
                % system contains an equation of an unknown type.
                %
                % 出错 sym/solve (第 293 行)
                % sol = eng.feval_internal('solve', eqns, vars, solveoptions);
                %
                % 出错 demo3 (第 5 行)
                % s=solve(eqns,[x y]);
                but i found that the solve function can include functions such as heaviside to indicate positive and negative:
                syms x y
                a = x y;
                b = floor(heaviside(x)) - 2*abs(2*heaviside(x) - 1) 2*floor(-heaviside(x)) 4;
                eqns = [a b*x == 1, a - b == 2];
                s = solve(eqns, [x y])
                % s =
                % 包含以下字段的 struct:
                %
                % x: -3/2
                % y: 11/2
                the piecewise function is divided into two sections, which is so complex, so this work must be encapsulated as a function to complete:
                function pwfunc=piecewisesym(x,waypoint,func,pfunc)
                % @author : slandarer
                gsign=[1,heaviside(x-waypoint)*2-1];
                lsign=[heaviside(waypoint-x)*2-1,1];
                insign=floor((gsign lsign)/2);
                onsign=1-abs(gsign(2:end));
                infunc=insign.*func;
                onfunc=onsign.*pfunc;
                pwfunc=simplify(sum(infunc) sum(onfunc));
                end
                function introduction
                • x : argument
                • waypoint : segmentation point of piecewise function
                • func : functions on each segment
                • pfunc : the value at the segmentation point
                example
                syms x
                % x waypoint func pfunc
                f=piecewisesym(x,[-1,1],[-x-1,-x^2 1,(x-1)^3],[-x-1,(x-1)^3]);
                for example, find the analytical solution of the intersection point between the piecewise function and f=0.4 and plot it:
                syms x
                % x waypoint func pfunc
                f=piecewisesym(x,[-1,1],[-x-1,-x^2 1,(x-1)^3],[-x-1,(x-1)^3]);
                % solve
                s=solve(f==.4,x)
                % s =
                %
                % -7/5
                % (2^(1/3)*5^(2/3))/5 1
                % -15^(1/2)/5
                % 15^(1/2)/5
                % draw
                xx=linspace(-2,2,500);
                f=matlabfunction(f);
                yy=f(xx);
                plot(xx,yy,'linewidth',2);
                hold on
                scatter(double(s),.4.*ones(length(s),1),50,'filled')
                precedent
                syms x y
                a=x y;
                b=piecewisesym(x,0,[2,1],2);
                eqns = [a b*x == 1, a - b == 2];
                s=solve(eqns,[x y])
                % s =
                % 包含以下字段的 struct:
                %
                % x: -3/2
                % y: 11/2

                  posted 2024-2-5,2:23

                  it is pretty easy to draw a cool heatmap for i have uploaded a tool to fileexchange:

                    posted 2024-2-5,2:13

                    t=0.2:0.01:3*pi;
                    hold on
                    plot(t,cos(t)./(1 t),'linewidth',4)
                    plot(t,sin(t)./(1 t),'linewidth',4)
                    plot(t,cos(t pi/2)./(1 t pi/2),'linewidth',4)
                    plot(t,cos(t pi)./(1 t pi),'linewidth',4)
                    ax=gca;
                    hlegend=legend();
                    pause(1e-16)
                    colordata = uint8([255, 150, 200, 100; ...
                    255, 100, 50, 200; ...
                    0, 50, 100, 150; ...
                    102, 150, 200, 50]);
                    set(ax.backdrop.face, 'colorbinding','interpolated','colordata',colordata);
                    set(hlegend.boxface,'colorbinding','interpolated','colordata',colordata)
                      网站地图