Struct as function input: different inputs?
2 views (last 30 days)
Show older comments
Hello,
I'm trying to write a method in a class, while this method follows this form:
[obj] = testStructInpt(obj);
and the content of this method is (for example):
function [obj] = testStructInpt(obj)
obj.otpt1 = randi(obj.input1);
what I want is input some properties of the object, obtain some output of the object.
However, if now I have some other properties other than obj.input1, for example, I have obj.input2 (input1 and input2 share the same method), and I write:
[obj] = testStructInpt(obj);
MATLAB gives me error:
Reference to non-existent field 'input2'.
So how can I write the method to allow different structural input?
Thanks!
0 Comments
Answers (1)
Adam
on 8 Mar 2017
Edited: Adam
on 8 Mar 2017
I'm not entirely sure what you are trying to do here, but you seem to be confusing the 'obj' input/output argument in a class function.
The first input argument to any non-static class function is always the object of the class itself. Personally I call this 'obj' always as you have, you can call it whatever you like though, it makes no difference, it will still always be the object of the class you are calling the function on.
If you want to pass in additional arguments to your function and assign these to the object then you pass these in as extra arguments e.g.
function [obj] = testStructInpt( obj, input1 )
obj.otpt1 = input1;
input1 can be whatever you like - double, struct, char, some other class object, etc.
The above syntax is for by-value classes (the default) which must return 'obj' as an output argument as well as having it as an input argument, otherwise anything that was set on obj will be lost because it will go out of scope when the function ends. Again this does not have to be called obj. It doesn't even have to be the same object as the 1st input argument though you will usually want it to be as your function is acting upon that object and you will then usually reassign it back to the same variable in calling the function e.g.
myObject = myObject.testStructInpy( input1 );
4 Comments
Adam
on 9 Mar 2017
Yes, you can remove the struct entirely from the function and just pass in an input and pass out an input and assign it to the struct afterwards. That makes a lot more sense from the function's point of view.
If you want to act on all fields of a struct then
doc structfun
can be used to make the code look neater at least.
See Also
Categories
Find more on Construct and Work with Object Arrays 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!