Tag Archive for 'surf'

MATLAB tip: Avoid loops and use surf command

Frequently we will get a function f(x,y) that we will need to plot. The naive way will be to generate an array for x and y and then iterate through all combinations and then use the plot3 function. Here is a sample:

  1. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2. % Assume function f(x,y)=-(x^2-2)^2 - (x^2-exp(y))^2
  3. % Crude Method
  4. x = -5:.1:5;
  5. y = 1:.1:4;
  6. points=[];
  7.  
  8. i=1;
  9. for xp = x
  10. for yp= y
  11. f = -(xp^2-2)^2 - (xp^2-exp(yp))^2;
  12. points(i,1) = xp;
  13. points(i,2) = yp;
  14. points(i,3) = f;
  15. i=i+1;
  16. end
  17. end
  18.  
  19. figure;hold on;grid on;
  20. xlabel('x');ylabel('y');zlabel('f');
  21.  
  22. plot3(points(:,1),points(:,2),points(:,3),'.');
  23.  
  24. hold off;

But this code is inefficient. Looping is to be avoided in MATLAB because operations on matrices are faster. Moreover, the plot3 function does not give shading. We get the following as the output:

Graph Using plot3

Avoiding loops, we can implement the above code in a different way. We avoid loops and use the surf command.

  1. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2. % Assume function f(x,y)=-(x^2-2)^2 - (x^2-exp(y))^2
  3. % Better Method
  4. x = -5:.2:5;
  5. y = 1:.2:4;
  6.  
  7. x_2d = ones(length(y),length(x))*diag(x);
  8. y_2d = diag(y)*ones(length(y),length(x));
  9.  
  10. func = -(x_2d.^2-2).^2 - (x_2d.^2-exp(y_2d)).^2;
  11.  
  12. figure;hold on;grid on;
  13.  
  14. xlabel('x');ylabel('y');zlabel('f');
  15. surf(x,y,func);
  16.  
  17. hold off;

We get the following output

Graph using surf and no loops

The trick in the above code involves creating the x_2d and y_2d array.

References:
(1) plot3
(2) surf