Effacer les filtres
Effacer les filtres

Storing Matrix in Workplace on each iteration

1 vue (au cours des 30 derniers jours)
Vladimir Palukov
Vladimir Palukov le 8 Août 2019
Commenté : Adam Danz le 12 Août 2019
Hello community,
This code uses a custom importfile function to get specific columns from .txt files and it works fine.
How can I extend the for loop so that the code:
a) saves a matrix(i) on each iterration as a value in the workplace
b) calculates the by element mean of all these matrices in a new matrix
files = dir('*.txt'); %get all text files of the present folder
N = length(files); %Total number of files
for i = 1:N
filename = files(i).name ;
A=importfile(files(i).name);
A=A{:,:}; %Convert the table into matrix
end
Thank you for your support!
V.

Réponse acceptée

Adam Danz
Adam Danz le 8 Août 2019
Modifié(e) : Adam Danz le 9 Août 2019
"How can I ... a) saves a matrix(i) on each iterration as a value in the workplace"
What I think you mean is to store each iteration of "A". Correct me if that's incorrect. The variable "A" is already stored in the workspace but you're overwriting it upon each iteration of the i-loop.
Below are 2 options.
Option 1: store each matrix in a cell array
% Create a cell array that will store your matrices
Amat = cell(size(files));
for i = 1:N
A=importfile(files(i).name);
Amat{i} = A{:,:}; % <---- store the matrix in the cell array
end
Option 2: if the matrices are all the same size, store them in a 3D array
Amat = nan(m,n,numel(files)); %where m and n are the expected dimension of the matrix
for i = 1:N
A=importfile(files(i).name);
Amat(:,:,i) = A{:,:}; % <---- store the matrix in a 3D array
end
"How can I... b) calculates the by element mean of all these matrices in a new matrix"
If you want the element-wise mean of each matrix (assuming they are all the same size),
% IF YOU CHOSE OPTION 1 ABOVE
% Assumes Amat has 1 row and f columns
[m,n] = size(Amat{1});
f = numel(Amat);
AmatMean = mean(reshape(cell2mat(Amat'),m,n,f),3);
% IF YOU CHOSE OPTION 2 ABOVE
AmatMean = mean(Amat,3);
  2 commentaires
Vladimir Palukov
Vladimir Palukov le 12 Août 2019
Thnaks for your quick reply!
Since the matrices are the same size option 2 worked like charm :)
Adam Danz
Adam Danz le 12 Août 2019
Good choice!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Data Type Conversion dans Help Center et File Exchange

Produits


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by