필터 지우기
필터 지우기

how to create csv file with dlmwrite for diffrent vector sizing?

조회 수: 3 (최근 30일)
nirit
nirit 2018년 10월 31일
댓글: nirit 2018년 10월 31일
hello, I have sevral of colums vector with different sizes, and I want to write them all to a csv file,in the following way:
for example, vec1=[11,12,13,14], vec2=[21,22,23]; vec3=[31,32,33,34,35,36] the output should be something like this:
line1: 11, 21,31
line2: 12, 22,31
line3: 13, 23,32
line4: 14, ,34
line5: , ,35
line6: , ,36
but instead the output is like this:
11,21,31
12,22,32
13,23,33
14,34
35
36
the code:
vec1=[11,12,13,14]; vec2=[21,22,23]; vec3=[31,32,33,34,35,36];
vec=[];
for i=1:max([length(vec1),length(vec2),length(vec3)])
if (i<=length(vec1))
vec=[vec,vec1(i)];
else vec=[vec,[]];
end
if (i<=length(vec2))
vec=[vec,vec2(i)];
else vec=[vec,[]];
end
if (i<=length(vec3))
vec=[vec,vec3(i)];
else vec=[vec,[]];
end
dlmwrite('test.csv', vec,'-append');
vec=[];
end
I tried replacing "vec=[vec,[]]" in the else with "vec=[vec,NaN]", and it worked, but I dont want to see "NaN" at all in the csv file. is there any other way to keep it blank? for record, I do not know in advance the length of each vector.
  댓글 수: 1
Stephen23
Stephen23 2018년 10월 31일
편집: Stephen23 2018년 10월 31일
"is there any other way to keep it blank?"
Not they way you are trying. Numeric array must contain numeric values, and [] is not a numeric value (it is an empty array). You could write your own export function using low-level operations (i.e. fprintf).
Or just use NaN.

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2018년 10월 31일
This is not possible using csvwrite or dlmwrite. You will need to fopen / fprintf / fclose.
  댓글 수: 1
nirit
nirit 2018년 10월 31일
this is what worked for me in the end:
vec1=[11,12,13,14]; vec2=[21,22,23]; vec3=[31,32,33,34,35,36];
fid = fopen('test.csv', 'w');
if fid == -1, error('Cannot open file for writing.'); end
for i=1:max([length(vec1),length(vec2),length(vec3)])
if (i<=length(vec1))
fprintf(fid,'%g,',vec1(i));
else fprintf(fid,',');
end
if (i<=length(vec2))
fprintf(fid,'%g,',vec2(i));
else fprintf(fid,',');
end
if (i<=length(vec3))
fprintf(fid,'%g,',vec3(i));
else fprintf(fid,',');
end
fprintf(fid,'\n');
end
fclose(fid);

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

madhan ravi
madhan ravi 2018년 10월 31일
편집: madhan ravi 2018년 10월 31일
instead of [] you can use 0 , you can omit it later on
else vec=[vec,0];
  댓글 수: 2
nirit
nirit 2018년 10월 31일
yes, but I dont want to omit the zeros of vectors (if the contain the value 0)
madhan ravi
madhan ravi 2018년 10월 31일
편집: madhan ravi 2018년 10월 31일
dlmwrite('test.csv', vec,'delimiter',',','TreatAsEmpty',1,'-append');

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

태그

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by