2

In Matlab, I don't know the best way to explain this except for an example. Let's say I have an array called tStart and a tDuration length:

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

Is there some way to get a new array such that it would be:

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

So what I want is to use the initial tStart array then make up a new array with the starting value and then next corresponding values for the length of tDuration.

If I do [tStart(1:end)+tDuration] I get an array of ending values, but how can I get the start, end, and all the values in between?

If I [tStart(1:end):tStart(1:end)+tDuration] I get an error.

Any help of a way to do this without a loop would be greatly appreciated.

1 Answer 1

5

I would use MATLAB's implicit expansion, reshape, and the ordering of 2d arrays.

First, create a 2d array containing the desired values from tStart:

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

tDurAdd = [0:tDuration].';  % numbers to add to tStart
tArray = tStart + tDurAdd;

This gives us

tArray =

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

These are the correct values, now we just have to reshape them to a row vector:

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

The final array is:

tResult =

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

Of course, this can all be done on one line:

tResult = reshape(tStart + [0:tDuration].', 1, []);
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your quick answer. Let me know if this should be another question, but when using this method in Scilab it gives an error of Inconsistent row/column dimensions. when trying to make tArray. Should it be the same for Scilab or will that be different? I know that reshape will need to be matrix.
@laxer I'm not that familiar with Scilab, but I gather from your error that it doesn't support implicit expansion. It also appears that it does not support the alternative in MATLAB, bsxfun. Sorry, but there's not much I can do for you.
It worked great in MatLab and that is what I specifically asked for, so thank you for your response. It was a lot of help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.