Raksha
Raksha

Reputation: 1699

How to 3D plot?

I'm having trouble letting the xi and yi ranges include anything but positive integer values because of the way I am storing data in the matrix (x and y values corresponding to the slot they are stored in), but I can't figure out a more clever way of doing it. Could someone please help me out? I'd like to be able to let xi = -30:30 and yi = -30:30.

function test3

f = @(x,y) y*sin(x) + sqrt(y);

    function p
        xi = 1:30;
        yi = 1:30;

        pts = zeros(size(xi,2),size(yi,2));
        for x = xi
            for y = yi
                pts(x,y) = pts(x,y) + f(x,y);
            end
        end
        surf(xi,yi,pts)
    end
p
end

Actual code that I'm working on:

function Eplot(z, w, R, Psi)
        ni = 0:2:4;
        mi = 0;
        xi = -30:30;
        yi = -30:30;

        pts = zeros(size(xi,2),size(yi,2));

        for n = ni
            for m = mi
                for x = xi
                    for y = yi
                        pts(x,y) = pts(x,y) + utot(z, x/10^4, y/10^4, n, m, w, R, Psi);
                    end
                end
            end
        end
        surf(xi,yi,pts)
    end
Eplot(zi, wi, Ri, Psii)

Upvotes: 0

Views: 38

Answers (1)

David
David

Reputation: 8459

Use meshgrid (as stated in the documentation for surf) and write your function f to use element-by-element operations so that it can take matrix input.

f = @(x,y) y.*sin(x) + sqrt(y);
xi = -30:30;
yi = -30:30;
[x,y]=meshgrid(xi,yi);
surf(xi,yi,f(x,y))

(Also, I hope you don'y really want to plot sqrt(y) for negative values of y)

If you can't write your function in such a way that allows you to give it vector arguments, then your for loop is a reasonable method, but I would write it like this:

f = @(x,y) y.*sin(x) + sqrt(y);
xi = -30:30;
yi = -30:30;
pts=zeros(length(xi),length(yi));
for ii=1:length(xi)
    for jj=1:length(yi)
        pts(ii,jj)=f(xi(ii),yi(jj));
        %// If `f` has more variables to iterate over (n, m, etc.) and sum, 
        %// do those loops inside the ii and jj loops
        %// I think it makes the code easier to follow
    end
end
surf(xi,yi,pts)

Upvotes: 2

Related Questions