Wallem89
Wallem89

Reputation: 314

How to create a vector in Matlab with two different step sizes?

I want to create a vector in Matlab with two step sizes that will alternate.

vector =
           0  50  51  101 102 152 etc.

So the step size is 50 and 1 which will alternate. How to write a script that will create this vector?

Upvotes: 1

Views: 921

Answers (3)

Divakar
Divakar

Reputation: 221574

Code

N = 6; %// Number of elements needed in the final output
sz1 = 50; %// Stepsize - 1
sz2 = 4; %// Stepsize - 2
startval = 8; %// First element of the output
vector = reshape(bsxfun(@plus,[startval startval+sz1]',[0:N/2-1]*(sz1+sz2)),1,[])

Output

vector =
     8    58    62   112   116   166

Note: For your problem, you need to use sz2 = 1 and startval = 0 instead.

Explanation

Internally it creates two matrices which when "flattened-out" to form vectors would resemble the two vectors that you have pointed out in the comments. You can get those two matrices with the following two sets of conditions.

Set #1: If you keep N = 6, sz1 = 50, sz2 = 0 and startval = 0 -

bsxfun(@plus,[startval startval+sz1]',[0:N/2-1]*(sz1+sz2))

gives us -

 0    50   100
50   100   150

Set #2: If you keep N = 6, sz1 = 0, sz2 = 1 and startval = 0 -

bsxfun(@plus,[startval startval+sz1]',[0:N/2-1]*(sz1+sz2))

gives us -

 0     1     2
 0     1     2

Good thing about bsxfun is that these two matrices can be summed internally to give the final output -

 0    51   102
50   101   152

Since, you needed the output as a vector, we need to flatten it out using reshape -

reshape(...,1,[])

giving us -

 0    50    51   101   102   152

Thus, we have the final code that was listed earlier.

Upvotes: 3

Luis Mendo
Luis Mendo

Reputation: 112689

Let the input data be

step1 = 50;
step2 = 1;
start = 0;
number = 9; %// should be an odd number

Then:

n = (number-1)/2;
vector = cumsum([start reshape(([repmat(step1,1,n); repmat(step2,1,n)]),1,[])]);

The result in this example is

vector =
     0    50    51   101   102   152   153   203   204

Upvotes: 0

Dev-iL
Dev-iL

Reputation: 24169

Here are some ideas I've been playing around with:

Initialization (comparable to Divakar's answer):

N = 6; %// Number of pairs in the final output
firstStep = 50;
secndStep = 1; 
startVal = 8; %// First element of the output

And then:

%// Idea 1:
V1 = [startVal cumsum(repmat([firstStep,secndStep],[1,N])) + startVal];

%// Idea 2:
trimVec = @(vec)vec(1:end-1);
V2 = trimVec(circshift(kron((startVal:firstStep:startVal + ...
               N*firstStep),[1,1]),[0,-1]) + kron((0:N),[1,1]));

Note that both of these vectors result in length = 2*N + 1.

The thing I'd like to point out is that if you create your vector of differences (e.g. [1 50 1 50 ...]), cumsum() really does the trick from there (you can also have more than 2 step sizes if you choose).

Upvotes: 0

Related Questions