Effacer les filtres
Effacer les filtres

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

9 vues (au cours des 30 derniers jours)
Kevin Egan
Kevin Egan le 13 Fév 2020
Commenté : Guillaume le 13 Fév 2020
I am trying to write a loop that creates a vector with blocks of data. How exactly would the above be possible?
  8 commentaires
Geoff Hayes
Geoff Hayes le 13 Fév 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 le 13 Fév 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.

Connectez-vous pour commenter.

Réponse acceptée

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

Connectez-vous pour commenter.

Plus de réponses (1)

Jon
Jon le 13 Fév 2020
Modifié(e) : Jon le 13 Fév 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

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by