How to write a for loop that creates a vector of [1:1000, 1001:2000,....,n]

14 views (last 30 days)
I am trying to write a loop that creates a vector with blocks of data. How exactly would the above be possible?
  8 Comments
Geoff Hayes
Geoff Hayes on 13 Feb 2020
by randomize the order of the results do you mean that rather than blocks of 1:1000, 1001:2000, etc. you want the 1:100000 randomly "distributed" across the 100 blocks?
Kevin Egan
Kevin Egan on 13 Feb 2020
Sorry again, I was hoping for something like [1:1000, 1001:2000, 4001:5000, 2001:3000....]
However, I think I was able to do that manually. Thanks for the help with reshape.

Sign in to comment.

Accepted Answer

the cyclist
the cyclist on 13 Feb 2020
% Define block size and number of blocks
blockSize = 1000;
numberBlocks = 50;
% Create vector of all values
A = 1:(blockSize*numberBlocks);
% Reshape into blocks
A = reshape(1:(blockSize*numberBlocks),blockSize,numberBlocks);
% Randomize the blocks
A = A(:,randperm(numberBlocks));
% Convert back to vector
A = A(:)';
Some of these steps could be combined, but I separated them for clarity.
I recommend testing this with a very small block size (maybe 3) and number of blocks (maybe 5) to verify it does what you want.
  1 Comment
Guillaume
Guillaume on 13 Feb 2020
Another way to obtain the same:
blockSize = 1000;
numberBlocks = 50;
A = reshape((randperm(numberBlocks) - 1) * blockSize + (1:blockSize)', 1, [])

Sign in to comment.

More Answers (1)

Jon
Jon on 13 Feb 2020
Edited: Jon on 13 Feb 2020
Just to make Geoff's suggestion more concrete, suppose you had a length 100000 vector of data points. You could put this into a matrix with 2000 rows and 50 columns. Each column would be a "block" of data if this is what you mean. To do this just use
X = reshape(x,2000,50)
Note, I still don't really understand what you are trying to do, but just to match up a little closer to your description if the vector x in the above expression went from 1:100000 then the first column of X would have the numbers 1 up to 1000 the next column would have the number 1001 up to 2000 etc

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!