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 次查看(过去 30 天)
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!

采纳的回答

Stephen23
Stephen23 2015-6-5
编辑:Stephen23 2015-6-5
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by