For loop to create a new matrix taking a cluster of columns from existing matrix
조회 수: 2 (최근 30일)
이전 댓글 표시
I have a matrix
FR_mat = randi(([1 20],1300,36);) % size 1300 rows, 36 columns
I would like to index this matrix FR_mat and and create a new matrix FR_sum with the outcome variables of my calculations.
I would like to take every 4 columns of the existing matrix and add it to each other so that 4 columns become one, with the values being the sum of all 4 columns. To visualize it, the following code is what I want to calculate. But I would like to do it in a For loop so that I have a shorter code and less work.
FR_sum(:,1) = FR_mat(:,1) + FR_mat(:,2) + FR_mat(:,3) + FR_mat(:,4);
FR_sum(:,2) = FR_mat(:,5) + FR_mat(:,6) + FR_mat(:,7) + FR_mat(:,8);
etc.
FR_sum(:,9) = FR_mat(:,33) + FR_mat(:,34) + FR_mat(:,35) + FR_mat(:,36);
This is what I tried so far:
k = 1;
for i = 1:11
i = i + 4
for j = 1:11
FR_sum(:,k) = sum(FR_mat(:,i:j);
k = k + 1 ;
end
end
Any ideas how I can manage this code?
Thank you for your help!
댓글 수: 0
채택된 답변
DGM
2021년 6월 4일
편집: DGM
2021년 6월 4일
Blockwise sum along dim 2 using a cell array
s = [1300 36]; % set the array size
FR_mat = randi([1 20],s(1),s(2));
C = mat2cell(FR_mat,s(1),ones(9,1)*4);
f = @(x) sum(x,2);
FR_sum = cell2mat(cellfun(f,C,'uniformoutput',false))
If you really want a loop version:
FR_sum2 = zeros(s(1),9);
for b = 1:9
FR_sum2(:,b) = sum(FR_mat(:,(1:4)+(b-1)*4),2);
end
FR_sum2
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!