Adding new fields to a structure using for loop

1 回表示 (過去 30 日間)
Christoph Bauer
Christoph Bauer 2011 年 8 月 10 日
Hello everyone,
I have a beginners question on working with structures and for loops: I used the following loop to read csv files into a structure (The ReadResearch function was written by a collegue to read certain csv files from one of our programs):
csvFiles = dir('*.csv');
numfiles = length(csvFiles);
for k= 1:numfiles
data=ReadResearch(csvFiles(k).name);
csvFiles(k).name=data;
end
My problem is that if I rerun the skript to read in more files it does not add these files to the structure but overwrites the existing one. can someone explain me what I have to change?
Thank you,
Christoph
  1 件のコメント
Oleg Komarov
Oleg Komarov 2011 年 8 月 10 日
Just for future reference (you question is clear): http://www.mathworks.com/matlabcentral/answers/6200-tutorial-how-to-ask-a-question-on-answers-and-get-a-fast-answer

サインインしてコメントする。

採用された回答

Oleg Komarov
Oleg Komarov 2011 年 8 月 10 日
If you already have a csvFiles, the first line should be:
csvFiles = [csvFiles dir('*.csv')];
Before that I would suggest to:
% Calculate offset
offs = numel(csvFiles);
% New loop
for k = offs:lenght(csvFiles)
...
end
Otherwise you will be reading all the files again and not just the new ones.
EDIT
Basically the robustified version reads:
if exist('csvFiles','var')
offs = numel(csvFiles);
csvFiles = [csvFiles dir('*.csv')];
else
offs = 0;
end
numfiles = length(csvFiles);
for k = offs+1:numfiles
data = ReadResearch(csvFiles(k).name);
csvFiles(k).name = data;
end

その他の回答 (1 件)

Christoph Bauer
Christoph Bauer 2011 年 8 月 31 日
thank you that solved it. Kind regards

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by