MATLAB: How to save a matrix that is set within a loop

loop

I use a loop to select certain rows from a matrix, satisfying the condition that the element in de first column of the row should be equal to 140,141,…,148.
w(1) starts at 140, so in de first time in the loop, the rows from the matrix are selected that have the element in the first column equal to 140. This happens 9 times, repeating for the other values of w.
I would like to store each "selection" from the matrix that is made in a matrix. I saw other similar questions but none of them helped me to solve this specific case.
M=9;
i=1;
w(1)=140; %select from frame 140
for m=1:M %to frame 148
w(m+1)=w(m)+i;
Info=allInfo((allInfo(:,1)==w(m)),:)
end
I hope someone can help me! Thanks in advance.

Best Answer

I would use accumarray, which makes this quick and efficient to implement:
>> M = randi([140,150],100,10); % Fake data matrix
>> V = 140:148; % the values that you want
>> X = 1:numel(V);
>> fun = @(v){M(M(:,1)==v,:)};
>> out = accumarray(X(:),V(:),[],fun); % the output
For example the first cell contains the rows matching V(1), the last one contains the rows matching V(end):
>> out{1}
ans =
140 145 148 145 147 150 141 149 146 150
140 146 142 148 149 146 140 145 143 142
140 140 144 142 141 146 141 146 144 149
140 144 140 140 144 146 142 147 145 141
140 142 148 142 147 145 145 146 146 140
140 150 146 147 149 150 147 140 148 148
140 144 142 142 145 144 144 149 142 143
140 150 141 147 146 144 140 148 142 147
140 144 140 143 142 146 143 149 141 145
140 146 142 145 145 148 141 142 148 149
>> out{end}
ans =
148 149 146 148 147 140 144 145 143 142
148 140 144 148 145 140 142 145 146 149
148 150 143 149 140 146 147 149 147 147
148 142 144 146 144 149 150 145 142 143
148 149 148 146 149 141 141 144 147 150
148 146 144 149 141 145 150 141 143 148
148 142 140 149 141 144 149 148 140 146
148 148 142 141 145 150 148 149 142 150
148 146 150 149 141 149 144 147 145 150
148 150 147 147 144 149 145 143 145 148
Whatever you do, do NOT try to write slow ugly hack code that creates those matrices using dynamic variables: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval