How can i append my csv file during looping?
조회 수: 3 (최근 30일)
이전 댓글 표시
This is what I currently have, but each loop will over-write the csv file, so i cannot append the csv file, is there anyu way to fix it ? -------------------------------------------------FileNames=dir('*.csv'); for i=1:length(FileNames) [num,txt,all] = xlsread(FileNames(i).name); fid = fopen(FileNames(i).name); hdrs = textscan(fid,'%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s',1,'delimiter',','); data = textscan(fid,'%s %s %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f',length(xlsread(FileNames(i).name))+1,'delimiter',','); fclose(fid); outCell = cell(size(data{1},1),length(hdrs)); for j=1:length(hdrs) if isnumeric(data{j}) outCell(:,j) = num2cell(data{j}); else outCell(:,j) = data{j}; end end z=outCell(1:length(xlsread(FileNames(i).name)),11); y= outCell(1:length(xlsread(FileNames(i).name)),1); x=outCell(1:length(xlsread(FileNames(i).name)),2); c=cell2mat(z);
댓글 수: 0
답변 (1개)
Michael Haderlein
2014년 8월 15일
I guess you don't want to append something to the csv file but to append something at your z,y,x variables, right? Also, I suppose that before the last line (c=...) there's a "end" keyword missing.
Then you need to use indexing. z,y,x built up from one-dimensional column arrays, so you can write
z(:,i)=outCell(...);
One comment on your z,y,x lines: Now you always read each file 4 (!) times, one time to get the data and another 3 times to just get the length. You can do that more efficiently by using the size of your data.
댓글 수: 2
Michael Haderlein
2014년 8월 15일
Please learn how to format your question that it's easier to read: http://www.mathworks.com/matlabcentral/answers/13205-tutorial-how-to-format-your-question-with-markup
However, I don't get an error. Maybe your different files have different lengths? I mean, different number of lines? Then, you cannot put them together to one matrix.
Also, I believe that you don't want to have the c=cell2mat(z) inside the for loop. It will be overwritten in every iteration. I suppose it should be outside after the loop. And still your code is very slow as you read every file 5 times. You should work on that.
참고 항목
카테고리
Help Center 및 File Exchange에서 Text Data Preparation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!