用meshgrid替换linspace

时间:2013-06-12 12:44:39

标签: matlab

我在for循环中使用meshgrid时出错了。我举一个例子来说明以下代码:

x=linspace(0,100,100);
y=linspace(0,100,100);
x0=[0 1 2 3];
y0=[4 5 6 7];
for i=1:4
   for j=1:length(x)
      for k=1:length(y)
         r(i,j,k)=sqrt((x(j)-x0(i)).^2+(y(k)-y0(i)).^2);
      end
   end
end

我想我在这里不必要地使用for循环并尝试用meshgrid替换它

[x,y]=meshgrid(0:1:100);
for i=1:4
   r(i,:,:)=sqrt((x(:)-x0(i)).^2+(y(:)-y0(i)).^2);
end

你能帮我改写一下这段代码吗?

2 个答案:

答案 0 :(得分:4)

x=linspace(0,100,100);

第一条评论:这不会产生[0 1 2 ... 100] - 为此你会使用linspace(0,100,101),因为0:100中有101个元素

你实际上非常接近这一点。只是不要将xx变成xx(:)(最后形状会出错):

[xx yy] = meshgrid(0:100, 0:100); % I like to use xx and yy to remind myself they are 2d...

x0=[0 1 2 3];
y0=[4 5 6 7];
for ii=1:4 % I use ii since i is also used as a built in variable with value sqrt(-1)
    r(ii,:,:) = sqrt((xx - x0(ii)).^2 + (yy - y0(ii)).^2);
end

离开最里面的for循环可能没问题。我想不出一种摆脱它的方法,它不会使你的代码不那么可读。

答案 1 :(得分:4)

没有循环没有meshgrid - 只需与bsxfun玩得开心:

dx = bsxfun( @minus, linspace( 0, 100, 100 ), x0' ).^2; %//'
dy = bsxfun( @minus, linspace( 0, 100, 100 ), y0' ).^2; %//'
r = sqrt( bsxfun( @plus, permute( dx, [2 1 3] ), ...
                         permute( dy, [2 3 1] ) ) );

瞧!

相关问题