1

Elements of a column matrix of non-sequential numbers (sourceData) should have their values incremented if their index positions lie between certain values as defined in a second column matrix (triggerIndices) which lists the indices sequentially.

This can be easily done with a for-loop but can it be done in a vectorized way?

%// Generation of example data follows
sourceData = randi(1e3,100,1);

%// sourceData = 1:1:1000; %// Would show more clearly what is happening
triggerIndices = randperm(length(sourceData),15);
triggerIndices = sort(triggerIndices);

%// End of example data generation

%// Code to be vectorized follows

increment = 75;
addOn = 100;
for index = 1:1:length(triggerIndices)-1
    sourceData(triggerIndices(index):1:triggerIndices(index+1)-1) = ...
        sourceData(triggerIndices(index):1:triggerIndices(index+1)-1) + addOn;
    addOn = addOn + increment;
end

sourceData(triggerIndices(end):1:end) = ....
    sourceData(triggerIndices(end):1:end) + addOn;
%// End of code to be vectorized
Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96

1 Answers1

1

How about replacing everything with:

vals = sparse(triggerIndices, 1, increment, numel(sourceData), 1);
vals(triggerIndices(1)) = addOn;
sourceData(:) = sourceData(:) + cumsum(vals);

This is basically a variant of run-length decoding shown here.

Community
  • 1
  • 1
Eitan T
  • 32,660
  • 14
  • 72
  • 109
  • 1
    Here's a slightly simpler version of the same thing: `incArray = zeros(size(sourceData)); incArray(triggerIndices) = increment; incArray(triggerIndices(1)) = addOn; sourceData = cumsum(incArray) + sourceData;` – Peter Sep 09 '13 at 16:04
  • Thanks @EitanT but I'm getting the error "Error using reshape. To RESHAPE the number of elements must not change." when I try those statements. – Ross J Donaldson Sep 09 '13 at 16:14
  • @Peter Thanks for the suggestion. I've simplified it even further :) – Eitan T Sep 09 '13 at 16:17
  • @RossJDonaldson Please try the amended answer. – Eitan T Sep 09 '13 at 16:17
  • 1
    Nice ;) I forgot about `sparse`. Except I think you want `vals(triggerIndices(1)) = addOn;` – Peter Sep 09 '13 at 16:19