matlab咋求和,如何在matlab中对双重求和进行向量化

更新时间:2023-06-21 02:48:35 阅读: 评论:0

matlab咋求和,如何在matlab中对双重求和进⾏向量化您可能已经知道,您应该在循环之前预先分配p:高一英语辅导书
p = zeros(Z, nR);
这可以防⽌数组p在每次迭代时增长,从⽽极⼤地加速循环.
你可以通过bsxfun对整个事物进⾏⽮量化:
% C ≣ M×N×R array of all products Rmn·J0m
C = bsxfun(@times, Rmn, J0m);
% D ≣ M×N×R×Z array of all products C·sinanz
D = bsxfun(@times, C, permute(sinanz, [3 1 4 2]));
% Sum in M and N directions, and re-order
erwinp = permute(sum(sum(D,1),2), [4 3 1 2]);
但我怀疑它会更快; MATLAB(读取:BLAS)与2D矩阵相当快,但对于更多D阵列通常不是很好.
我建议你阅读约bsxfun;它也是以你描述的⽅式将J0m数组减少到M×R的⽅法.
当然,你可以通过正确定义你的变量来摆脱这种变换,所以让我们在循环代码和⽮量化代码的“理想”版本中做⼀个⼩测试:
%% Initialize some variableschristmas card
% Number of tests
TESTS = 1e4;
% Your dimensions
M = 5; nR = 4;
N = 2; Z = 3;
% Some dummy data
Rmn = rand(M,N);
sinanz = rand(N,Z);
J0m = rand(M,nR); % NOTE: J0m doesn't have to be 3D anymore by using bsxfun
关于中秋节的手抄报的图片
%% Test 1: your own version, optimized
% Start test
初一暑假英语日记start = tic;
% Repeat the test a couple of times to get a good average
for ii = 1:TESTS
p1 = zeros(Z,nR);
for iR = 1:nR
p1(:, iR) = sum( bsxfun(@times,Rmn,J0m(:, iR)), 1 )*sinanz;
end
end
stop = toc(start);
% Average execution time
fprintf(1, 'Average time of looped version: %f conds.\n', stop/TESTS); %% Vectorized version, using 4D arrays:
% Don't make the permutes part of the test
J0m = permute(J0m, [1 3 2]);
sinanz = permute(sinanz, [3 1 4 2]);
% Start test
start = tic;
% Repeat the test a couple of times to get a good average
for ii = 1:TESTS
C = bsxfun(@times, Rmn, J0m);
D = bsxfun(@times, C, sinanz);
p2 = sum(sum(D,1),2);
end
stop = toc(start);
% Average execution time
fprintf(1, 'Average time of vectorized version: %f conds.\n', stop/TESTS); %% Check for equality
maxDifference = max(max(p1 - squeeze(p2)'))
结果:
Average time of looped version : 0.000054 conds.
Average time of vectorized version: 0.000023 conds.
maxDifference =
4.440892098500626e-016
这看起来还不错!但是,使⽤
M = 50; nR = 40;
N = 20; Z = 30;fashionably late
junk是什么意思你得到
Average time of looped version : 0.000708 conds.
Average time of vectorized version: 0.009835 conds.
maxDifference =
8.526512829121202e-014
爱霸词典
因此⽮量化版本⽐循环变体慢⼀个数量级.
当然,your mileage may vary,但带回家的消息是你应该期望这种差异会越来越⼤,越来越差.
美国留学新政策
所以,最后:
>如果您的尺⼨很⼤,请坚持使⽤.如果它们很⼩,也可以使⽤循环 – 它在眼睛上⽐⽮量化版本容易得多:)>确保预先分配p变量>使⽤bsxfun减少内存占⽤(但不会提⾼速度)2011年浙江省高考分数线

本文发布于:2023-06-21 02:48:35,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/90/152101.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:量化   循环   变量   应该   预先   代码
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图