Matlab Basics: Vectorize function on the real plane

140 Views Asked by At

I'm trying to visualise the behavior of the L2 norm by plotting a 2D surface in 3D using Matlab. I currently have the following code;

x = -5:0.1:5;
y = x;
[X, Y] = meshgrid(x);

l2n = zeros(length(x), length(y));

for i=1:length(x)
  for j=1:length(y)
      xi = x(i);
      yj = y(j);
      v = [xi yj];

      l2n(i, j) = norm(v, 2);
  end
end

figure;
surf(X, Y, l2n);

Which produces a nice plot;

L2 norm

I am currently using nested for loops because I don't know how to write a function of X, Y (or x, y) that takes [xi, yj] as an argument (as the norm function does). Is there a way to vectorize these loops into a single line function?

1

There are 1 best solutions below

1
On BEST ANSWER

One possibility is to vectorize with arrayfun:

l2n = arrayfun(@(v1, v2) norm([v1 v2], 2), X, Y);

This collects in turn one element of X and the corresponding element of Y and finds the 2-norm of the vector formed by those two elements, just like your double for loop does.