Reputation: 747
I have a matrix 63 rows x 7 columns
I want to select every 7th,8th,9th ongoing value in each column and add them to create a new value.
i.e.
7 8 9th added to a new value
16 17 18th added to a new value...etc
25 26 27th
34 35 36th
43 44 45th
52 53 54th
61 62 63th
So I should end up with a 7x7 matrix.
Without doing this manually, is there a simple command so that if the dimensions of the matrix changes, the output will always be correct?
Upvotes: 0
Views: 944
Reputation: 74930
You can do that easily with a bit of reshaping.
originalMatrix = (1:63)'*(1:7); %'
[nRows,nCols] = size(originalMatrix); %# =63 in this example
stepSize = 9;
nTriplets = floor(nRows/stepSize); %# =7 in this example
%# create index list
idx = bsxfun(@minus,stepSize:stepSize:nRows,[2 1 0]'); %'
idx = idx(:); %# reshape to a vector
%# create 3-by-7-by-7 array from original matrix
tmpMatrix = reshape(originalMatrix(idx,:),3,nTriplets,nCols);
%# sum along dim 1 (to sum e.g. the 7th, 8th, and 9th value)
result = squeeze(sum(tmpMatrix,1));
result =
24 48 72 96 120 144 168
51 102 153 204 255 306 357
78 156 234 312 390 468 546
105 210 315 420 525 630 735
132 264 396 528 660 792 924
159 318 477 636 795 954 1113
186 372 558 744 930 1116 1302
Upvotes: 1
Reputation: 1499
If I had understood your question properly, this slip of code should do what you want. But I admit, maybe it's not the most efficient Matlab code ever-written...
k = 9; n = 7; m = k*n; % 63
A = randi(5,m,n);
startIdx = k*(1:n)+n-k;
endIdx = k*(1:n);
B = zeros(n,n);
for i = 1:n
tmp = A(startIdx(i):endIdx(i),:);
B(i,:) = sum(tmp,1);
end
Upvotes: 1
Reputation: 4330
matrix=(1:63)'*(1:7);
n=7;
startind = n:(n+2):size(matrix,1);
endind = (n+2):(n+2):size(matrix,1);
tmp=cumsum(matrix);
tmp(endind,:)-tmp(startind,:)
This will, of course, only work if startind
and endind
have the same length, which would not be the case for, say, a matrix of size 62x7.
Upvotes: 1