加速Octave / matlab代码中的循环

时间:2017-03-26 16:43:10

标签: matlab for-loop octave vectorization

完成这些循环需要大约2分钟才知道除了改变颜色数量或使用的细胞数量之外我怎么能加快速度/创建图像?矢量化会有所帮助,如果是这样,我该怎么做?基本上它会在每个循环中创建一个动画帧

见下面的代码

clear all,clf reset,tic,clc,clf

rgb1 = jet(256);
len1 = size(rgb1,1);
RGB1 = permute(rgb1,[3 1 2]);
figure; imshow(RGB1); %bar of colors
len2 = 200;

num2use=numel(num2str(length(rgb1)))+1 %count how many values and add 1. can use R also
lead_zeros=strcat('%0',num2str(num2use),'d'); %creates variable needed

for ii=0:length(rgb1)
  ii
  rgb1_shift=circshift(rgb1,[ii,:]);

  t = linspace(0,4*pi,len2);
  x = t.*cos(t);
  y = t.*sin(t);
  %rgb2 = interp1(1:len1,rgb1,linspace(1,len1,len2));
  rgb2 = interp1(1:len1,rgb1_shift,linspace(1,len1,len2));

  [xg,yg] = meshgrid([-t(end:-1:2) t],[-t(end:-1:2) t]);
  RGB2 = zeros([size(xg) 3]);
  % interpolate for the desired coordinates
  for c = 1:3
      RGB2(:,:,c) = griddata(x,y,rgb2(:,c),xg,yg);
  end
  imwrite(RGB2,strcat('/tmp/img2/',sprintf(lead_zeros, ii),'_spiral','.png')); %will create file without borders and use any resize in repmat

end


fprintf('\nfinally Done-elapsed time -%4.4fsec- or -%4.4fmins- or -%4.4fhours-\n',toc,toc/60,toc/3600);

Ps:我使用Octave 4.0,类似于matlab

1 个答案:

答案 0 :(得分:1)

这里有一些错误,修复它们可以大大提高速度:

  1. 将所有循环独立变量移出循环。
    即在循环外移动t = linspace(0,4*pi,len2);x = t.*cos(t);y = t.*sin(t);[xg,yg] = meshgrid([-t(end:-1:2) t],[-t(end:-1:2) t]);RGB2 = zeros([size(xg) 3]);
  2. 直接由RGB2定义RGB2(:) = cat(3, griddata(x,y,rgb2(:,1),xg,yg), griddata(x,y,rgb2(:,2),xg,yg), griddata(x,y,rgb2(:,3),xg,yg)),以避免在内存中重新分配数组。
  3. 如果你解释一下你究竟想要什么,我们可能会更有帮助。