Store specific loop outputs in separate matrix

4 次查看(过去 30 天)
I'd like to create a matrix as shown below, but without having to repeatedly copy and paste the same line. However, each output has 3 columns; after each iteration columns, 1 and 2 stay the same, only 3 changes. I need to keep each different 3rd column.
T = readtable('data.txt');
T=table2array(T);
[i,~,j] = unique(T(:, [2,3]), 'rows');
A1 = [i, accumarray(j, T(:, 7), [], @mean)];
A2 = [i, accumarray(j, T(:, 8), [], @mean)];
A3 = [i, accumarray(j, T(:, 9), [], @mean)];
A4 = [i, accumarray(j, T(:, 10), [], @mean)];
Final = [A1(:,:),A2(:,3),A3(:,3)]; %A4(:,3), and so on
I tried the following, but can't quite get it right
T = readtable('data.txt');
T=table2array(T);
[i,~,j] = unique(T(:, [2,3]), 'rows');
for x = 7:10
A = [i, accumarray(j, T(:, x), [], @mean)];
m(i,:) = [i A(:,2) A(:,3)];
end

回答(1 个)

ag
ag 2025-4-21
Hi Kathy,
To create a matrix with multiple columns calculated from different columns of the input data, you can use a loop to automate the process of creating each matrix A and then combine them into a final matrix. The below code snippet demonstrates how to achieve the same:
% Rest of the code
% Initialize a matrix to store the final result
% The number of columns will be 2 (from i) + number of columns in the loop (4 in this case)
numColumns = 4; % Change this if you have more columns to process
Final = zeros(size(i, 1), 2 + numColumns);
% Assign the first two columns from 'i'
Final(:, 1:2) = i;
% Loop through the desired columns
for x = 7:10
% Calculate the mean for the current column
A = [i, accumarray(j, T(:, x), [], @mean)];
% Store the third column of A into the appropriate column of Final
Final(:, x - 4) = A(:, 3);
end
Kindly adjust the range for the loop and the "numColumns" variable if you have more columns to process.
Hope this helps!

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by