I have a set of values (say 20 values) in an array .
A = [1:20]
I want to divide it in to subsets of known size. If I want to divide it in to 4 sets of size 5 then I can use
y = reshape(A,5,4)'
But my problem is when I dont have matching multiples of sizes. Say I want to divide array in to sets of 3. So there will be 7 sets but the last set will be short.
what exactly I want is
a1= [1 2 3]
a2= [4 5 6]
a3= [7 8 9]
a4= [10 11 12]
a5= [13 14 15]
a6= [16 17 18]
a7= [19 20]
How can I do this kind of subgrouping to a vector in MATLAB?
You can use
y = mat2cell(A,1, diff([0:n:numel(A)-1 numel(A)]));
Then a1=y{1} and so on.
You'll need to write your own function for this. For example:
A = 1:20;
n = length(A);
x = 3;
y = ceil(n/x);
out = cell(y,1);
for i = 1:y
startIdx = x*(i-1)+1;
endIdx = min(startIdx + x - 1,n);
out{i} = A(startIdx:endIdx);
end
Then you can access each row in the cell array:
a1 = out{1};
a2 = out{2};
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With