1

This is my actual code:

Lr = linspace(100,300,10);
vi = linspace(10,30,10);
vf = linspace(10,30,10);
b = linspace(0.5,1.2,10);
h = linspace(0.3,0.8,10);
Rc = [1000, 1500, 2000, 2500, 3000, 3500;
      29, 22.4, 17.3, 13.4, 10.4, 8];
rti = randi(5, 10, 1, 10, 10, 10, 10);
for kk = 1:rows(Lr)
  for jj = 1:length(vi)
    for ll = 1:length(vf)
      for mm = 1:length(b)
        for nn = 1:length(h)
          ratt(kk,1,jj,ll,mm,nn) = Rc(2,rti(kk,1,jj,ll,mm,nn));
        endfor
      endfor
    endfor
  endfor
endfor

In this example, all the vectors are of length 10, but in the real code, they can be from 1 to 100. How can I remove all these loops?

Eliahu Aaron
  • 4,103
  • 5
  • 27
  • 37

1 Answers1

0
  1. Get all values to ratt from Rc as a 1D array.
  2. Reshape ratt to a 6D array as in the original code.

Code:

ratt = Rc(2, rti(1:rows(Lr), 1, 1:length(vi), 1:length(vf), 1:length(b), 1:length(h)));
ratt = reshape(ratt, [rows(Lr), 1, length(vi), length(vf), length(b), length(h)]);

Testing: To test the equality and speed of the vectorized and non-vectorized codes I wrote the following code:

Lr = linspace(100,300,10);
vi = linspace(10,30,10);
vf = linspace(10,30,10);
b = linspace(0.5,1.2,10);
h = linspace(0.3,0.8,10);
Rc = [1000, 1500, 2000, 2500, 3000, 3500;
      29, 22.4, 17.3, 13.4, 10.4, 8];
rti = randi(5, 10, 1, 10, 10, 10, 10);

disp('Non-vectorized:')
tic
for kk = 1:rows(Lr)
  for jj = 1:length(vi)
    for ll = 1:length(vf)
      for mm = 1:length(b)
        for nn = 1:length(h)
          ratt(kk,1,jj,ll,mm,nn) = Rc(2,rti(kk,1,jj,ll,mm,nn));
        endfor
      endfor
    endfor
  endfor
endfor
toc

disp('')

disp('Vectorized:')
tic
ratt1 = Rc(2, rti(1:rows(Lr), 1, 1:length(vi), 1:length(vf), 1:length(b), 1:length(h)));
ratt1 = reshape(ratt1, [rows(Lr), 1, length(vi), length(vf), length(b), length(h)]);
toc

disp('')

if(isequal(ratt,ratt1))
  disp('ratt is equal to ratt1!')
else
  disp('ratt is not equal to ratt1!')
endif

Output:

Non-vectorized:
Elapsed time is 0.16697 seconds.

Vectorized:
Elapsed time is 0.000309944 seconds.

ratt is equal to ratt1!
Eliahu Aaron
  • 4,103
  • 5
  • 27
  • 37