LenaH
LenaH

Reputation: 323

Vectorized loop in Matlab

Very simple question, but I didn't find anything...

I have to split my code in different sections and run it the following way, because some matrices are built from left to right and some from right to left via backwards induction. For example, if I split it in 3 sections, I would run the sections in this order:

1, 2, 3,

1, 2,

1,

1, 2,

1, 2, 3.

So I need a vector [1, 2, 3, 1, 2, 1, 1, 2, 1, 2, 3]. But since the number of sections is much greater than 3, I want to build a general vector that goes:

1 : noSections

1 : noSections - 1

...

1

...

1 : noSections

How would I do that?

Upvotes: 0

Views: 45

Answers (1)

Nemesis
Nemesis

Reputation: 2334

You can use arrayfun which is pretty nice for your job.

cell2mat(arrayfun(@(x)1:x, [n:-1:1 2:n], 'UniformOutput', false))

Explanation:

[n:-1:1 2:n] % create the vector for the last element of each row, i.e. the vector [n, n-1, ..., 1, 2, ..., n]

@(x)1:x % Generate a 1:x vector for each x, this is done for each element of the previous vector

For your example:

n = 3;
cell2mat(arrayfun(@(x)1:x, [n:-1:1 2:n], 'UniformOutput', false))

ans =

     1     2     3     1     2     1     1     2     1     2     3

Upvotes: 3

Related Questions