【问题标题】:Matlab make new array of values without a loopMatlab在没有循环的情况下创建新的值数组
【发布时间】:2020-06-21 18:15:00
【问题描述】:

在 Matlab 中,除了一个例子,我不知道最好的解释方式。假设我有一个名为 tStart 的数组和一个 tDuration 长度:

tStart = [3,8,15,20,25];
tDuration = 2;

有没有办法得到一个新的数组:

[3,4,5,8,9,10,15,16,17,20,21,22,25,26,27]

所以我想要的是使用初始 tStart 数组,然后用起始值组成一个新数组,然后是 tDuration 长度的下一个对应值。

如果我这样做[tStart(1:end)+tDuration],我会得到一个结束值数组,但是我怎样才能得到开始、结束以及它们之间的所有值呢?

如果我[tStart(1:end):tStart(1:end)+tDuration] 会出错。

如果能提供任何不使用循环的方法,我们将不胜感激。

【问题讨论】:

    标签: arrays matlab matrix indexing


    【解决方案1】:

    我会使用 MATLAB 的隐式扩展、重塑和二维数组的排序。

    首先,创建一个包含来自tStart 的所需值的二维数组:

    tStart = [3,8,15,20,25];
    tDuration = 2;
    
    tDurAdd = [0:tDuration].';  % numbers to add to tStart
    tArray = tStart + tDurAdd;
    

    这给了我们

    tArray =
    
        3    8   15   20   25
        4    9   16   21   26
        5   10   17   22   27
    

    这些是正确的值,现在我们只需要将它们重塑为行向量:

    tResult = reshape(tArray, 1, []);
    

    最终的数组是:

    tResult =
    
        3    4    5    8    9   10   15   16   17   20   21   22   25   26   27
    

    当然,这一切都可以在一行中完成:

    tResult = reshape(tStart + [0:tDuration].', 1, []);
    

    【讨论】:

    • 感谢您的快速回答。让我知道这是否应该是另一个问题,但是在 Scilab 中使用此方法时,在尝试制作 tArray 时会出现 Inconsistent row/column dimensions. 错误。 Scilab 应该是一样的还是会有所不同?我知道reshape 必须是matrix
    • @laxer 我对 Scilab 不太熟悉,但我从您的错误中得知它不支持隐式扩展。它似乎也不支持 MATLAB 中的替代方案bsxfun。抱歉,我能为你做的不多。
    • 它在 MatLab 中运行良好,这是我特别要求的,所以感谢您的回复。帮了大忙!
    猜你喜欢
    • 2019-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    • 2021-11-18
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    相关资源
    最近更新 更多