How can I create variables in a loop assigning matrix values in a .dat file?

I have a series of .dat files (files_i, with i=1,...,6) consisting of an mxn matrix, and want to create vectors t_i such that the i-th vector takes the 1st column of the i-th file (t_1 = files_1(:,1), t_2 = files_2(:,1)), and so on.
I would like to do that in a loop, but can't find an efficient way to do so.
Any ideas? Thanks in advance

 Accepted Answer

You have to follow something like the below:
F = dir('*.dat'); % get all .dat files in folder
nF = length(F) ; % number of files
iwant = zeros(m,nF) ; % m is number of rows of the matrix in the .dat file
for i = 1:nF % loop for each file
% load the file
A = load(F(i).name) ;
iwant(:,i) = A(:,1) ; % where A is the matrix in the .dat file
end

3 Comments

Thank you! I get the idea, but I still have some issues:
The A matrix has the same name as the .dat file, so each time I want to create the matrix, I have to do it by accessing the file's name.
Also, what happens if I don't know the number of rows of the matrix in the .dat file? (In this case I know it, but just curious...)
Thanks and sorry for the inconvenience
Use: A = load(file) ; If you don't know the number of rows...load the first file, get the dimensions and run the loop for rest of the files.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!