Filter löschen
Filter löschen

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

10 Ansichten (letzte 30 Tage)
I am trying to write a loop that creates a vector with blocks of data. How exactly would the above be possible?
  8 Kommentare
Geoff Hayes
Geoff Hayes am 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 am 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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

the cyclist
the cyclist am 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 Kommentar
Guillaume
Guillaume am 13 Feb. 2020
Another way to obtain the same:
blockSize = 1000;
numberBlocks = 50;
A = reshape((randperm(numberBlocks) - 1) * blockSize + (1:blockSize)', 1, [])

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Jon
Jon am 13 Feb. 2020
Bearbeitet: Jon am 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

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by