Info

この質問は閉じられています。 編集または回答するには再度開いてください。

How to add a new column to several matrices

1 回表示 (過去 30 日間)
George Moore
George Moore 2020 年 1 月 19 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
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!

回答 (1 件)

Thiago Henrique Gomes Lobato
Thiago Henrique Gomes Lobato 2020 年 1 月 19 日
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 件のコメント
George Moore
George Moore 2020 年 1 月 19 日
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!

Translated by