How can I contour plot a custom function?

安稳与你 提交于 2019-12-23 16:27:25

问题


I have a custom function which returns either 0 or 1 depending on two given inputs:

function val = myFunction(val1, val2)

  % logic to determine if val=1 or val=0

end

How can I create a contour plot of the function over the x,y coordinates generated by the following meshgrid?

meshgrid(0:.5:3, 0:.5:3);

This plot will just simply display where the function is 0 or 1 on the contour map.


回答1:


If your function myFunction is not designed to handle matrix inputs, then you can use the function ARRAYFUN to apply it to all the corresponding entries of x and y:

[x,y] = meshgrid(0:0.5:3);      %# Create a mesh of x and y points
z = arrayfun(@myFunction,x,y);  %# Compute z (same size as x and y)

Then you could use the function CONTOUR to generate a contour plot for the above data. Since your z data only has 2 different values, it would probably make sense for you to only plot one contour level (which would be at a value of 0.5, halfway between your two values). You might also want to instead use the function CONTOURF, which produces color-filled contours that will clearly show where the ones and zeroes are:

contourf(x,y,z,1);  %# Plots 1 contour level, filling the area on either
                    %#   side with different color


NOTE: Since you are plotting data that only has ones and zeroes, plotting contours may not be the best way to visualize it. I would instead use something like the function IMAGESC, like so:

imagesc(x(1,:),y(:,1),z);

Keep in mind the y-axis in this plot will be reversed relative to the plot generated by CONTOURF.




回答2:


The following will do it:

function bincontour
    clear; clc;

    xrange = 0:.5:3;
    yrange = 1:.5:5;
    [xmesh, ymesh] = meshgrid(xrange, yrange);
    z = arrayfun(@myFunction, xmesh, ymesh);

    contourf(xrange, yrange, z, 5)
end

function val = myFunction(val1, val2)
    val = rand() > 0.5;
end


来源:https://stackoverflow.com/questions/3784059/how-can-i-contour-plot-a-custom-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!