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 Ansicht (letzte 30 Tage)
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!

Akzeptierte Antwort

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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by