If I have a 2100 x 16 matrix, how can I specify for a certain value to go in to rows 1:84, then another into 85:169, and repeat this 25 times in some kind of loop?

1 visualizzazione (ultimi 30 giorni)
Hi,
Sorry for the random question. I'm trying to simulate data to follow a certain format of output file. I already have a script to generate simulated survey data. Basically, I want to add in subject numbers without doing it manually. So, if subject 1 has data from rows 1:84, subject 2 from rows 85:169, down until subject 25 who ends at row 2100... I want to have a column that has "1" for the first 84 rows, then 2 for the next 84 rows, etc.
I'm sure there's a straightforward way to do this with a for loop, I just can't seem to figure it out.
Thanks for any help!

Risposta accettata

Stephen23
Stephen23 il 5 Giu 2015
Modificato: Stephen23 il 5 Giu 2015
Don't bother with a loop, in MATLAB vectorized code is neater and faster:
>> A = 1:4; % the group enumeration
>> N = 3; % the number of rows in each group
>> reshape(repmat(A,N,1),[],1)
ans =
1
1
1
2
2
2
3
3
3
4
4
4
You can then simply allocate those values to any column of your matrix, here are three options (you did not specify how you want this to be allocated):
X(:,1) = reshape(repmat(A,N,1),[],1); % into existing first column
X(:,end+1) = reshape(repmat(A,N,1),[],1); % into a new trailing column
X = [reshape(repmat(A,N,1),[],1), X]; % into a new first column
  2 Commenti
Stephen23
Stephen23 il 5 Giu 2015
My pleasure. It takes a while to learn a tool like MATLAB, but it is faster and more enjoyable when you learn the efficient ways of doing things.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by