Borrar filtros
Borrar filtros

Storing Matrix in Workplace on each iteration

1 visualización (últimos 30 días)
Vladimir Palukov
Vladimir Palukov el 8 de Ag. de 2019
Comentada: Adam Danz el 12 de Ag. de 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.

Respuesta aceptada

Adam Danz
Adam Danz el 8 de Ag. de 2019
Editada: Adam Danz el 9 de Ag. de 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 comentarios
Vladimir Palukov
Vladimir Palukov el 12 de Ag. de 2019
Thnaks for your quick reply!
Since the matrices are the same size option 2 worked like charm :)
Adam Danz
Adam Danz el 12 de Ag. de 2019
Good choice!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Data Type Conversion en Help Center y File Exchange.

Productos


Versión

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by