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 visualización (últimos 30 días)
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!

Respuesta aceptada

Stephen23
Stephen23 el 5 de Jun. de 2015
Editada: Stephen23 el 5 de Jun. de 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 comentarios
Chelsea
Chelsea el 5 de Jun. de 2015
Wow, that is a lot more clean looking than the loop I was trying to create :P Thanks!!
Stephen23
Stephen23 el 5 de Jun. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by