Importing matrices in text files and creating a structure with 100 entries

Hello there,
I was hoping that somebody could perhaps help me out with a problem that I have. I'm only learning how to use matlab.
I have 100 4x4 matrices in .txt files in a folder.
How could I import them and create a structure with 100 entries and in each entry there would be one matrix.
The reason I ask is because I'm trying to get the average of these matrices and this post provides a solution if the matrices are in this format.
Thank you for your help
Regards
John

Answers (1)

Also note, that if they're all the same size, you could stack them along the third dimension and then take the mean of the first and second dimension which would leave you with each matrice's mean.

7 Comments

Hi Sean thank you for replying,
I think I have the process to load the files down below? To be honest I just don't know who to create the structure and entries.
I would really appreciate some help or advice on the next step?
Regards
John
files = dir(fullfile(pwd,'*.txt'));
for k = 1 : numel(files)
%%%% reading the txt file
fid01 = fopen(fullfile(pwd,files(k).name));
idx = 0; tmparray = [];
tline = fgetl(fid01);
while ischar(tline)
idx = idx + 1;
tmparray(idx,:) = str2num(tline);
tline = fgetl(fid01);
end
fclose(fid01);
%%%% Create the structure and entries
end
too much effort, use importdata() and a cell array (you can convert to struct later):
C = cell(100,1);
for ii = 1:100
C{ii} = importdata(filename(ii))
end
Hi again,
Please bear with me. So if the text files are called matrix1.txt, matrix2.txt etc
C = cell(100,1);
for ii = 1:100
C{ii} = importdata(matrix(ii))
end
Apologies if this is a very basic question!
importdata(['matrix' num2str(ii) '.txt'])
You're welcome!
Were you able to get it working?
Hi again,
Honestly I haven't been able to get it to work
This is the code I'm using
C = cell(100,1);
for ii = 1:100
C{ii} = importdata(['matrix' num2str(ii) '.txt']) ;
end
but I'm getting this error
??? Error using ==> importdata at 123
Unable to open file.
The files are just text files each containing a 4x4 matrix
Could you offer any further suggestions?
Thank you

This question is closed.

Asked:

on 14 Feb 2012

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!