MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

### Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

# Enable Parfor or Vectorization

Asked by Brian on 27 Jun 2012

I'm looking for a faster way to calculate these loops. I've read some about vectorization on Loren's page but I'm not sure that would apply here. I also have the parallel computing toolbox, but because of how I'm writing to my preallocated data arrays, I get the message "Valid Indices are restricted in parfor loops." Can someone take a look at my code and make a suggestion how to get parfor to work and/or use vectorization? Essentially I'm calculating a 21 day return for every security, for every day (past 21 days) in my dataset.

Thanks a lot, Brian

```parfor i = 1:SecCnt
tickidx = strcmp(UnqSec(i,1),Cusips);
for d = 21:DatesCnt
RollRtns(i*(d-21)+1,1) = prod(Rtns(Rtns(:,2)>d-21 & Rtns(:,2)<=d & tickidx));
RollCusips(i*(d-21)+1,1) = UnqSec(i,1);
RollDates(i*(d-21)+1,1) = UnqDates(d,1);
end
end
```

## 1 Comment

Brian on 2 Jul 2012

I have edited this code so that it now works in parallel but is still rather slow. I've read about vectorization and I'm wondering if it's possible for this code. This takes about 30 seconds to in serial and 10 seconds to run in parallel because of the large data overhead. I'm just trying to speed this up a bit.

```parfor i = 1:SecCnt
NestLoop = NaN(1,DatesCnt-21);
tickidx = strcmp(UnqSec(i,1),Cusips);
for d = 21:DatesCnt
NestLoop(d-20) = prod(Rtns(Rtns(:,2)>d-21 & Rtns(:,2)<=d & tickidx));
end
RollRtns(i,:) = NestLoop;
end
```

Contact us