根据存储在第二个矩阵中的范围更改一个MatLab矩阵中的值

时间:2013-09-09 14:22:43

标签: matlab for-loop vectorization

非连续数字(sourceData)的列矩阵的元素如果其索引位置位于第二列矩阵(triggerIndices)中定义的某些值之间,则其值应增加指数顺序。

这可以通过for循环轻松完成,但可以以矢量化方式完成吗?

%// 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

1 个答案:

答案 0 :(得分:1)

如何用以下内容替换所有内容:

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

这基本上是here显示的游程解码的变体。