Rick T
Rick T

Reputation: 3389

Speeding up for loops in Octave / matlab code

It takes about 2 minutes to complete these loops does any know how I can speed this up / create the images faster other than changing the amount of colours or the amount of cells used? Would vectorization help at all and if so how should I do this? Basically it creates a frame of an animation each loop

see code below

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: I'm using Octave 4.0 which is similar to matlab

Upvotes: 0

Views: 725

Answers (1)

Royi
Royi

Reputation: 4953

There are few mistakes here which fixing them can improve the speed greatly:

  1. Move all loop independent variable out of the loop.
    Namely move, 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]); and RGB2 = zeros([size(xg) 3]); outside the loop.
  2. Define RGB2 directly by RGB2(:) = cat(3, griddata(x,y,rgb2(:,1),xg,yg), griddata(x,y,rgb2(:,2),xg,yg), griddata(x,y,rgb2(:,3),xg,yg)) to avoid reallocation of the array in memory.

If you explain what exactly you're trying to of we might be even more helpful.

Upvotes: 1

Related Questions