Clear Filters
Clear Filters

Storing Matrix in Workplace on each iteration

1 view (last 30 days)
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.

Accepted Answer

Adam Danz
Adam Danz on 8 Aug 2019
Edited: Adam Danz on 9 Aug 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 Comments
Vladimir Palukov
Vladimir Palukov on 12 Aug 2019
Thnaks for your quick reply!
Since the matrices are the same size option 2 worked like charm :)

Sign in to comment.

More Answers (0)

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!