如何在matlab中优化此集成代码?

时间:2017-01-27 23:53:20

标签: matlab optimization vectorization

使用Matlab Profiler我发现这行代码正在造成一个巨大的瓶颈,并减慢了我的程序。 wxyz都是包含相同尺寸(A x B x C)的3D矩阵,其中A不等于B且不等于C.有没有办法优化这行代码以更快地运行?

dt = .5;

for t = 1: tstop
    w(:,:,t+1)= sum( dt*(x(:,:,t:-1:1).*(y(:,:,1:t) - .002).*z(:,:,1:t)),3);
end

1 个答案:

答案 0 :(得分:0)

如果您将某些字词组合在for循环之外,则可以获得2x提升:

p = dt*(y - .002).*z;
for t = 1: tstop
    w(:,:,t+1)= sum( x(:,:,t:-1:1).*p(:,:,1:t), 3);
end

现在更容易注意到我们在第三维度上计算xp的卷积。如果该维度C(或tstop)很大,您可以尝试内联或优化这些卷积。

我会将3D矩阵重塑为2D矩阵,将前2个维度分组,并将时间维度保留为第二个维度。然后,您可以尝试使用conv2 fft fft(如this answer中所述)tstop = C执行行方式卷积。在下面找到一个X = reshape(x, [A*B, C]); % reshape to 2D Y = reshape(y, [A*B, C]); Z = reshape(z, [A*B, C]); P = dt*(Y - .002).*Z; % grouped terms z__ = zeros(A*B, C); % zero-padding W = real(ifft(fft([z__, X]').*fft([z__, P]'))'); % column-wise fft W = [zeros(A*B, 1), W(:, 1:C)]; % first half w = reshape(W, [A, B, C+1]); (和零填充)的解决方案,假设为A

B

结果相同,取决​​于CA=13B=14,这可以为您带来巨大的性能提升。 C=1155original: 1.026312 seconds grouping terms: 0.509862 seconds FFT: 0.033699 seconds <Style x:Key="ButtonStyle" TargetType="{x:Type Button}"> <Setter Property="VerticalContentAlignment" Value="Center" /> <Setter Property="HorizontalContentAlignment" Value="Center" /> <Setter Property="SnapsToDevicePixels" Value="True" /> <Setter Property="BorderThickness" Value="1" /> <Setter Property="BorderBrush" Value="{StaticResource Button.BorderBrush}" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Button}"> <Border x:Name="Button_Border" Background="{StaticResource Button.BackgroundBrush}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="5,2,5,2" CornerRadius="2"> <Border.RenderTransform> <ScaleTransform x:Name="Button_ScaleTransform" CenterX="0.5" CenterY="0.5" /> </Border.RenderTransform> <VisualStateManager.VisualStateGroups> <VisualStateGroup> <VisualState x:Name="Normal" /> <VisualState x:Name="Pressed"> <Storyboard> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="Button_Border" Storyboard.TargetProperty="RenderTransform.ScaleX"> <EasingDoubleKeyFrame KeyTime="0:0:0.0" Value="0.9" /> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="Button_Border" Storyboard.TargetProperty="RenderTransform.ScaleY"> <EasingDoubleKeyFrame KeyTime="0:0:0.0" Value="0.9" /> </DoubleAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="MouseOver" /> <VisualState x:Name="Focused" /> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <ContentPresenter /> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style>

的示例
Script Component