Info

This question is closed. Reopen it to edit or answer.

How to add a new column to several matrices

1 view (last 30 days)
George Moore
George Moore on 19 Jan 2020
Closed: MATLAB Answer Bot on 20 Aug 2021
Hi, I currently have a series of 100 files (each a matrix with 2 columns but varying rows). I would like to add a third column to eah file each containing one number in all the rows.
For example, the first file should have a third column with the numbers 1 entered in all rows, the second file with the number 2, the third with 3 and so on.
I have managd to add a new column to one fo the files using this code.
file1(:,3) = 1
However I would like to be able to do this automatically for all 100 files without having to do this for each file. Is there a way to create a loop to do this for me?
Thanks!

Answers (1)

Thiago Henrique Gomes Lobato
How you read your files? It should actually be very straight forward, something like this should help (Read it mosty as a pseudo-code):
Nfiles = 100;
for idx = 1:Nfiles % loop for all your files
File = load(['blabla_',num2str(Nfiles),'.mat']); % Insert here how you read the file
File(:,3) = idx; % idx will always increase
save(['blabla_',num2str(Nfiles),'.mat'],'File') % Save the file back
end
If your files can't be easily indexed (are not numbered from 1 to 100) you can use the dir function to list all names and then loop through it.
  1 Comment
George Moore
George Moore on 19 Jan 2020
Thanks Thiago! At first it would not seem to work, but by changing the Nfiles to idx in the following code it has now worked. Thank you very much for your help!
Nfiles = 100;
for idx = 1:Nfiles % loop for all your files
File = load(['blabla_',num2str(idx),'.mat']); % Insert here how you read the file
File(:,3) = idx; % idx will always increase
save(['blabla_',num2str(idx),'.mat'],'File') % Save the file back
end

Community Treasure Hunt

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

Start Hunting!