Why do I receive "Cannot write value: unsupported class struct error" when writing a structure using the FWRITE function?
    12 views (last 30 days)
  
       Show older comments
    
    MathWorks Support Team
    
 on 27 Jun 2009
  
    
    
    
    
    Edited: MathWorks Support Team
    
 on 26 Apr 2023
            If I try to write a structure to a file using the FWRITE function, i receive the following error:
 ??? Error using ==> fwrite
 Cannot write value: unsupported class struct
For example:
a.name='Mathworks';
a.number=10;
fid = fopen('testfile.txt','w+');
fwrite(fid,a)
Accepted Answer
  MathWorks Support Team
    
 on 27 Jun 2009
        The ability to write a structure to a file using FWRITE is not available in MATLAB.
To work around this issue, write each field of the structure sequentially to the file. This can be done either by calling the FWRITE function from the command line for every field, or by writing a program similar to the one shown below to loop through each variable and write it to the file:
%%%Open the file in the write mode, fid is the id of the file.
%%%Assume the structure is the variable ‘a’
%%%As a sample, let ‘a’ have two fields: name and number
a.name='Mathworks';
a.number=10;
NEWLINE = sprintf('\n');
fields=fieldnames(a);
for i=1:length(fields)
      fields(i);
      classes{i}=eval(['class(a.' fields{i} ')']);
end
fid = fopen('testfile.txt','w+');
for j = 1: length(fields)
      if ~strcmp(classes(j),'char')
          str = num2str(eval(['a.' fields{j} ]));
      else        
          str = eval(['a.' fields{j} ]);
      end
      fwrite(fid, str, 'uchar');    
end
fwrite(fid, NEWLINE, 'char');
%%%Call this loop if you have multiple structures too.
%%%Close the file.
1 Comment
  Vandana Ravichandran
    
 on 22 Feb 2017
				
      Edited: MathWorks Support Team
    
 on 26 Apr 2023
  
			MATLAB converts .NET object to native MATLAB data types. In your case, System.Int64 should be converted to int64 scalar. Refer the following page from the documentation for more information: https://www.mathworks.com/help/matlab/matlab_external/handling-net-data-in-matlab.html
If you just want to save the workspace structure variables for future use inside MATLAB, you can use the "save" function. If you want to save the structure to a text file, you can convert the structure array to a table using "struct2table" function. Subsequently, you can use "writetable" function to write the table to a comma-delimited text file.
More Answers (0)
See Also
Categories
				Find more on Cell Arrays in Help Center and File Exchange
			
	Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
