【问题标题】:efficient storing of matlab shape functionsmatlab形状函数的高效存储
【发布时间】:2013-07-17 14:14:33
【问题描述】:

我正在尝试找到一种尽可能高效的方法来存储和调用我的 matlab 形状函数。我有一个区间 x=linspace(0,20) 和一个位置向量

count = 10;
for i=1:count
    pos(i)=rand()*length(x);
end

现在,我想在每个位置放置pos(j) 形状函数,例如具有紧凑支持的高斯核或帽子函数或类似的东西(应该可以轻松更改原型函数)。该功能的支持由所谓的平滑长度h 控制。 所以我在 .m 文件中构建了一个函数,例如(例如三次样条)

function y = W_shape(x,pos,h)

l=length(x);
y=zeros(1,l);
if (h>0)
    for i=1:l
        if (-h <= x(i)-pos && x(i)-pos < -h/2)
            y(i) = (x(i)-pos+h)^2;
        elseif (-h/2 <= x(i)-pos && x(i)-pos <= h/2)
            y(i) = -(x(i)-pos)^2 + h^2/2;
        elseif (h/2 < x(i)-pos && x(i)-pos <=h)
            y(i) = (x(i)-pos-h)^2;
        end
    end
else
    error('h must be positive')
end

然后在区间 x 上构造我的函数

w = zeros(count,length(x));
for j=1:count
    w(j,:)=W_shape(x,pos(j),h);
end

到目前为止一切都很好,但是当我制作 x=linspace(0,20,10000)count=1000 时,我的计算机(Intel Core-i7)需要几分钟才能计算出全部内容。 由于它应该是某种 PDE 求解器,因此必须在每个时间步(在特定情况下)都执行此过程。 我认为我的问题是,我使用x 作为函数调用的参数并存储每个函数,而不是只存储一个并转移它,但是我的 matlab 知识不是很好,所以有什么建议吗?仅供参考:我需要两个或多个功能支持相交的区域的积分......当我在 1D 中完成这个时,我想为 2D 功能做它,所以无论如何它必须是高效的

【问题讨论】:

    标签: matlab function spline


    【解决方案1】:

    一种初始向量化方法是移除 W_shape 函数中的 for 循环:

    for i=1:l
        if (-h <= x(i)-pos && x(i)-pos < -h/2)
            y(i) = (x(i)-pos+h)^2;
        elseif (-h/2 <= x(i)-pos && x(i)-pos <= h/2)
            y(i) = -(x(i)-pos)^2 + h^2/2;
        elseif (h/2 < x(i)-pos && x(i)-pos <=h)
            y(i) = (x(i)-pos-h)^2;
        end
    end
    

    可以变成

    xmpos=x-pos; % compute once and store instead of computing numerous times
    inds1=(-h <= xmpos) & (xmpos < -h/2);
    y(inds1) = (xmpos(inds1)+h).^2;
    inds2=(-h/2 < xmpos) & (xmpos <= h/2);
    y(inds2) = -(xmpos(inds2).^2 + h^2/2;
    inds3=(h/2 < xmpos) & (xmpos <=h);
    y(inds3) = (xmpos(inds3)-h).^2;
    

    可能有比这更好的优化。

    编辑: 我忘了提,你应该使用分析器找出真正慢的地方!

    profile on
    run_code
    profile viewer
    

    【讨论】:

    • 哇,帮了大忙!谢谢。现在我知道,最消耗 cpu 的部分不是我的形状函数(尽管您的示例极大地提高了效率),而是我的函数找到了交点并计算了这些区域的积分。
    猜你喜欢
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    • 2013-01-20
    相关资源
    最近更新 更多