【问题标题】:Changing values in one MatLab matrix based on ranges stored in a second matrix根据存储在第二个矩阵中的范围更改一个 MatLab 矩阵中的值
【发布时间】:2013-09-09 14:22:42
【问题描述】:

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

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

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

【问题讨论】:

    标签: matlab for-loop vectorization


    【解决方案1】:

    如何将所有内容替换为:

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

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

    【讨论】:

    • 这里有一个稍微简单的版本:incArray = zeros(size(sourceData)); incArray(triggerIndices) = increment; incArray(triggerIndices(1)) = addOn; sourceData = cumsum(incArray) + sourceData;
    • 感谢@EitanT,但我收到错误“使用重塑时出错。要重塑元素的数量不能改变。”当我尝试这些陈述时。
    • @Peter 感谢您的建议。我进一步简化了它:)
    • @RossJDonaldson 请尝试修改后的答案。
    • 很好 ;) 我忘了sparse。除了我认为你想要vals(triggerIndices(1)) = addOn;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 1970-01-01
    • 1970-01-01
    • 2015-07-23
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多