简体   繁体   English

嵌套的匿名函数,包括arrayfun

[英]Nested anonymous functions including arrayfun

I'm trying to do something like the following code: 我正在尝试执行以下代码:

k = linspace(a,b);
x = c:0.01:d;
% k and x are of different sizes
f = @(s) arrayfun(@(t) normcdf(s, b0+b1*t, sigma), x);
y = arrayfun(f, k);

I get the following error 我收到以下错误

Error using arrayfun Non-scalar in Uniform output, at index 1, output 1. Set 'UniformOutput' to false . 使用arrayfun在统一输出中在索引1,输出1处非标量时出错。将'UniformOutput'设置为false

I'm trying to avoid using a for loop for each element in k. 我试图避免对k中的每个元素使用for循环。
Also, for each result matching an element in k, I need to do another small calculation 另外,对于每个与k中的元素匹配的结果,我需要做另一个小的计算

Example with a loop: 循环示例:

for i=1:m  % m is the number of elements in k
    f = @(t) normcdf(k(i), b0+b1*x, sigma);
    y = arrayfun(f, x);
    res(i) = trapz(x,y);
end

any idea how can I get the same result as the for loop with the first method? 知道如何使用第一种方法获得与for循环相同的结果吗?
and why am I getting the error? 为什么我会收到错误消息?

I would suggest the following: 我建议以下内容:

k = linspace(a,b);
x = c:0.01:d;
[X,K] = meshgrid(x,k)

y = arrayfun(@(p,t) normcdf(p, b0+b1*t, sigma), K(:), X(:))
res = cumtrapz(x,y)

Untested though as you gave no example data and desired results. 尽管您未提供示例数据和所需结果,但未经测试。 Maybe you need to swap the order of x and k as well as X and K to get the desired result. 也许您需要交换xk以及XK的顺序才能获得所需的结果。 (or use ndgrid instead of meshgrid , has the same effect) (或使用ndgrid代替meshgrid ,具有相同的效果)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM