test_mult_ndxsd.m
来自「麻省理工学院的人工智能工具箱,很珍贵,希望对大家有用!」· M 代码 · 共 73 行
M
73 行
% Here we give an example of how we can multiply two tables using two 1D indicesfoo = 1;ns = 2*ones(1,20);if foo bigdom = [3 4 7 8 10]; smalldom = [4 10];else bigdom = 1:5; smalldom = [3 5];end% compute using dpotbigpot = dpot(bigdom, ns(bigdom), rand(ns(bigdom)));smallpot = dpot(smalldom, ns(smalldom));newbigpot = divide_by_pot(bigpot, smallpot);%newbigpot = multiply_by_pot(bigpot, smallpot);S = struct(bigpot); bigT = S.T;S = struct(smallpot); smallT = S.T;S = struct(newbigpot); newbigT = S.T;% naive implementationif ~fooi = 1;for e=1:ns(5) for c=1:ns(4) % c chnages fastest smallndx = subv2ind(ns(smalldom), [c e]); assert(isequal(smallndx, i)) offset = (c-1)*4 + (e-1)*16; for a=1:ns(1) for b=1:ns(2) for d=1:ns(4) bigndx = subv2ind(ns(bigdom), [a b c d e]); base = subv2ind(ns(bigdom), [a b 1 d 1]); % clamp the outer loop to its 1st iteration assert(isequal(offset + base, bigndx)) newbigT2(bigndx) = bigT(bigndx) * smallT(smallndx); end end end % next a i = i + 1; endendassert(approxeq(newbigT, newbigT2))end[small_ndx, diff_ndx] = mk_ndx(bigdom, smalldom, ns);%%%% Use offset and base to do multiplicationnewbigT3 = zeros(ns(bigdom));S = length(small_ndx);D = length(diff_ndx);for i=1:S for j=1:D k = small_ndx(i) + diff_ndx(j) + 1; newbigT3(k) = bigT(k) * smallT(i); endendassert(approxeq(newbigT, newbigT3))% Use 2D indicesndx = 1 + repmat(diff_ndx, S, 1) + repmat(small_ndx(:), 1, D); % ndx(i,j) = k abovenewbigT4(ndx(:)) = bigT(ndx(:)) .* repmat(smallT(:), D, 1);assert(approxeq(newbigT, newbigT4))% for i, for j is better for cache locality% but the repmat method implements for j, for i (both give equivalent results)tmp.small = small_ndx;tmp.diff = diff_ndx;newbigT5 = mult_by_table_ndx(bigT, smallT, tmp);assert(approxeq(newbigT, newbigT5))
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?