필터 지우기
필터 지우기

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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by