assignment of an object to a vector
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi all and happy new year!
I have the following simple problem. I have a function say
res=myfunc(a,b,c)
res=zeros(2,1);
res(1)=a+log(b)+cos(c);
res(2)=(b-c)/a;
end
in addition, I have a class say "myclass". When I call the function myfunc with numerical values for a, b and c, the result is as expected. However, when I call myfunc with inputs of class myclass, I get an error saying: "??? In an assignment A(I)=B, the number of elements in B and I must be the same"
clearly, numel(res(1)) is 1 and numel(a+log(b)+cos(c)) is also 1 although res(1) and a+log(b)+cos(c) are of different classes.
A simple workaround is to write the function above differently
res=myfunc2(a,b,c)
res=[
a+log(b)+cos(c)
(b-c)/a
];
end
that is, rather that declaring a vector as in the first case, I construct a vector directly. In this case things work fine as well. I just don't know how to make the code work for the first case as well.
Any thoughts?
Thanks, Pat.
0 commentaires
Réponse acceptée
Matt J
le 5 Jan 2013
Modifié(e) : Matt J
le 5 Jan 2013
clearly, numel(res(1)) is 1 and numel(a+log(b)+cos(c)) is also 1.
That's not clear at all, since you haven't showed us how LOG, COS, and PLUS were overloaded for myclass in order to obtain the expression a+log(b)+cos(c). We have no idea based, on what you've shown, what this expression produces.
Also, MATLAB does not allow res(1) and res(2) to be of different classes. Therefore when you do
res(1) = a+log(b)+cos(c)
MATLAB tries to convert a+log(b)+cos(c) from whatever class it is to 'double', the same class as res(2). You haven't mentioned if or how you've overloaded the double() function to accomplish this.
5 commentaires
Matt J
le 5 Jan 2013
Modifié(e) : Matt J
le 5 Jan 2013
Then why not use myfunc2? That looks like a perfectly appropriate thing to do anyway, and as a bonus makes things class-independent. Also, what about the 2nd option that I gave you, i.e., start by assigning res(end)? Then assign the remaining elements in any order you wish. Just make sure the constructor of your class can accept nargin=0 arguments.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Argument Definitions dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!