フィルターのクリア

assignment of an object to a vector

1 回表示 (過去 30 日間)
Patrick Mboma
Patrick Mboma 2013 年 1 月 5 日
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.

採用された回答

Matt J
Matt J 2013 年 1 月 5 日
編集済み: Matt J 2013 年 1 月 5 日
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 件のコメント
Patrick Mboma
Patrick Mboma 2013 年 1 月 5 日
編集済み: Patrick Mboma 2013 年 1 月 5 日
If I initialize res to a myclass object then the function probably won't work for doubles... and I would like to have a procedure that is independent of the input function.
I have a better understanding of the process although my problem remains unsolved. If the left hand side is a double, then matlab calls the double method on the right hand side of the equality. Ideally, the output vector should be resized on the fly to the dimensions of the right hand side. But I guess this is too much asking...
Matt J
Matt J 2013 年 1 月 5 日
編集済み: Matt J 2013 年 1 月 5 日
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.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by