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 view (last 30 days)
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!

Accepted Answer

Stephen23
Stephen23 on 5 Jun 2015
Edited: Stephen23 on 5 Jun 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 Comments
Stephen23
Stephen23 on 5 Jun 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.

Sign in to comment.

More Answers (0)

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!