For loop to create a new matrix taking a cluster of columns from existing matrix
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Akzeptierte Antwort
DGM
am 4 Jun. 2021
Bearbeitet: DGM
am 4 Jun. 2021
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
Siehe auch
Kategorien
Mehr zu Matrices and Arrays 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!