0

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?

1
  • In one sentence: I want to build a vector [1:noSections, 1:noSections-1, 1:noSections-2, ..., 1:1, 1:2, 1:3, ..., 1:noSections]. Commented Feb 23, 2017 at 8:59

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

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.