Struct as function input: different inputs?
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Adam
2017-3-8
编辑:Adam
2017-3-8
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 个评论
Adam
2017-3-9
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!