using fopen inside of a class
3 views (last 30 days)
Show older comments
Hello there,
I am a graduate student looking to make a gcode writing script for our machine. I figured the easiest way would be to create a class with readable methods for me and my partner to share. We have previously been using fopen() to open a text file and write the gcode using fprintf statements, and I was hoping to translate that into a class; But I'm having problems with assigning the file to the object property.
Here's the class definition:
classdef Welder
properties
gcodefile
txtout = fopen(gcodefile,'w');
end
methods
function startUp(obj,Amperage)
obj.txtout = fopen(obj.gcodefile,'w');
fprintf(obj.txtout,"G0 G90 G54 G17 G40 G49 G80\nG21\nM3 S%.0f\nG4 P1.0\n",Amperage);
end
function moveX(obj,X)
fprintf(obj.txtout,'G1 X%.2f\n',X);
end
end
And here's the code in which I create an object of the welder class:
ArcNid = ARCNID;
% Startup
ArcNid.gcodefile = "GCodeOut.txt";
ArcNid.startUp(row,S);
ArcNid.turnArcOn(S,PF);
However, running this code yields the error message -
Error using U_Notch_SQR_Maker
Invalid default value for property 'txtout' in class 'ARCNID':
Unrecognized function or variable 'gcodefile'.
I've tried moving the definition of the txtout property around, but when changing the value inside of another method (I.E, the startUp method), the class property doesn't change, and any subsequent methods yield a similar 'unknown definition' error. Alternatively, I'm unsure if txtout should even be a property; I'm unused to matlab classes/etc., but I thought fopen returned essentially an interger file identifier, which sounds like it should then be a property.
Thanks in advance for the help!!
2 Comments
Walter Roberson
on 3 Mar 2024
Your class does not initialize the property gcodefile
Your class tries to assign txtout the result of fopen() . But you also assign the same thing in startUp.
Answers (1)
Steven Lord
on 4 Mar 2024
txtout (I believe) is a public property by default, so any idea why it won't budge?
Your class is a value class. Value classes and handle classes behave differently in MATLAB. In particular, "If you pass this variable to a function to modify it, the function must return the modified object as an output argument."
So as you've written it, your startUp function modifies the copy of the object that was created for the method to operate on. When your method exits, because you're not returning that copy, the copy gets discarded along with the rest of the method workspace.
The easiest solution, if you want your class to be a value class, is to return the copy as an output argument.
See this documentation page for some discussion of the pros and cons of making your class a value class or a handle class.
See Also
Categories
Find more on Startup and Shutdown 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!