【问题标题】:Matlab: arrayfun, two matrices X,Y as components of the vectorMatlab:arrayfun,两个矩阵X,Y作为向量的分量
【发布时间】:2019-11-14 20:19:41
【问题描述】:

假设 X, Y 是给定区间内的坐标矩阵

xc = 0, yc = 0
xl = linspace(xc - 10, xc + 10, 2);
yl = linspace(yc - 10, yc + 10, 2);
[X,Y] = meshgrid(xl,yl);

而 fun 是一些函数 test(v) 的句柄

fun = @(v)test(v);

如何组合两个矩阵 X, Y 以便它们代表向量 v 的分量 x,y

res = arrayfun(fun, [X,Y]); //First processed X and then Y

不幸的是,这个解决方案不起作用....

修改函数时还有另外一种方式,让两个参数xy被传递

fun = @(x, y)test(x, y);
res = arrayfun(fun, X, Y); //This works well

但是,如果存在任何解决方案,我想保留函数的接口。

感谢您的帮助。

【问题讨论】:

    标签: arrays matlab function parameter-passing


    【解决方案1】:
    • fun 重新定义为fun = @(x, y)test([x,y]);

    无需修改函数test()

    xc = 0;
    yc = 0;
    xl = linspace(xc - 10, xc + 10, 2);
    yl = linspace(yc - 10, yc + 10, 2);
    [X,Y] = meshgrid(xl,yl);
    
    % Given function test
    test =@(v)v(1) + v(2);
    
    
    % pass x, y as a vector  
    fun = @(x, y)test([x,y]);
    
    
    res = arrayfun(fun, X, Y);
    
    % X =
    
       -10    10
       -10    10
    
    % Y =
    
       -10   -10
        10    10
    
    % fun(x, y) = x + y
    
    % res =
    
       -20     0
         0    20
    
    

    【讨论】:

      【解决方案2】:

      来自Matlab doc

      B = arrayfun(func,A) 将函数func 应用于A 的元素,一次一个元素

      B = arrayfun(func,A1,...,An)func 应用于数组A1,...,An 的元素,因此B(i) = func(A1(i),...,An(i))

      所以你以错误的方式使用arrayfun

      改用一个 for 循环或两个嵌套循环。

      for i=1:size(X,1)
          for j=1:size(X,2)
          res(i,j)=fun([X(i,j),Y(i,j)])
          end
      end
      

      你想做什么?

      另外,在 Matlab 中,您应该使用 % 而不是 // 进行评论

      这些是一些相关的问题:

      arrayfun when each row of the array is an input

      Passing a vector as multiple inputs to a function

      【讨论】:

      • @Amin:我想避免两个嵌套循环,让代码更清晰。一般来说,对于大数据,这种方法比使用 for 循环要快得多。
      • @justik: arrayfun 是一个 for 循环。为什么说它比 for 循环快得多?
      • @Cris:你说得对,没有可测量的速度增量,我试过了。并在这里确认mathworks.com/matlabcentral/answers/…
      猜你喜欢
      • 2020-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多