Clear Filters
Clear Filters

Using fprintf: string in array is NaN

9 views (last 30 days)
Lisa M
Lisa M on 5 Feb 2020
Edited: Stephen23 on 5 Feb 2020
Hi Everyone,
Please, see my code below. My data.name variable which is a string contains only NaN values when printed.
Any suggestions on how to solve this issue? Thanks in advance.
data.x= [0;1;0;1]
data.y= [1;1;1;1]
data.z= [0;0;0;0]
data.name={'Laura'; 'Caroline'; 'Lynne'; 'Charlie'}
input=[data.x data.y data.z convertCharsToStrings(data.name)];
fmt = repmat(',%.12g',1,size(input,2)); % numeric format for input
fmt = [fmt(2:end),'\n'];
[fid,msg] = fopen('test.csv','wt');
assert(fid>=3,msg)
fprintf(fid,'\n');
fprintf(fid,'\n');
fprintf(fid,fmt,input.');
fclose(fid);

Accepted Answer

Stephen23
Stephen23 on 5 Feb 2020
Edited: Stephen23 on 5 Feb 2020
No need to convert data to string:
>> data.x = [0;1;0;1];
>> data.y = [1;1;1;1];
>> data.z = [0;0;0;0];
>> data.name = {'Laura'; 'Caroline'; 'Lynne'; 'Charlie'};
>> tmp = [num2cell([data.x,data.y,data.z]),data.name].';
>> fmt = [repmat('%.12g,',1,3),'%s\n'];
>> fprintf(fmt,tmp{:})
0,1,0,Laura
1,1,0,Caroline
0,1,0,Lynne
1,1,0,Charlie

More Answers (0)

Categories

Find more on Convert Image Type in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!