Store specific loop outputs in separate matrix

6 visualizzazioni (ultimi 30 giorni)
kathy
kathy il 1 Feb 2018
Risposto: ag il 21 Apr 2025
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

Risposte (1)

ag
ag il 21 Apr 2025
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!

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by