フィルターのクリア

Storing Matrix in Workplace on each iteration

1 回表示 (過去 30 日間)
Vladimir Palukov
Vladimir Palukov 2019 年 8 月 8 日
コメント済み: Adam Danz 2019 年 8 月 12 日
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.

採用された回答

Adam Danz
Adam Danz 2019 年 8 月 8 日
編集済み: Adam Danz 2019 年 8 月 9 日
"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 件のコメント
Vladimir Palukov
Vladimir Palukov 2019 年 8 月 12 日
Thnaks for your quick reply!
Since the matrices are the same size option 2 worked like charm :)
Adam Danz
Adam Danz 2019 年 8 月 12 日
Good choice!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by