필터 지우기
필터 지우기

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 CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by