Function with input an array of classes.
조회 수: 9 (최근 30일)
이전 댓글 표시
Maybe it's because I have a lot of programming experience in C/C++, but I am trying to build a function inside a class that takes a whole array of classes as an input. Matlab always returns "too many arguments". This is how I tried to do it.
classdef agent
properties
r
v
id
end
methods
function y=mean_distance(a)
S=sum(norm(a.r-this.r));
y=S/(size(a)-1)
%I also need a random access iterator to a, like disp(a(i).r(1));
end
end
Thanks. EDIT: class should probably have a handle for this to work, but I am unfamiliar with handles. Reading some relative tutorials.
댓글 수: 0
채택된 답변
Andrew Newell
2011년 3월 18일
I can't run your code because there are a lot of undefined terms, but I can see two problems. First, if you run
a(2).view(a(2),a)
it's like having 3 arguments. You should call your function using one of these two equivalent forms:
view(a(2),a)
a(2).view(a) % The a(2) is considered the first argument
Second,
n=size(agents)
will give you a vector [1 10], which will give you an error when you get to the loop
for i=1:n
...
댓글 수: 0
추가 답변 (4개)
Andrew Newell
2011년 3월 18일
To set values in this object, you must have a class constructor. Now suppose a is an array of length 2 with a.r having values 1 and 2. Then if you type
a.r
You'll get something like this:
ans =
1
ans =
2
It's a comma-separated list, not a vector. To bundle them together, you'll need square brackets, like this:
function y=mean_distance(a,this)
y=mean(norm([a.r]-[this.r]));
end
A handle is not necessary for this problem.
EDIT: By the way, I substituted mean for your method, but maybe you have some reason for dividing by length(a)-1 instead of length(a)?
댓글 수: 0
Philip Borghesani
2011년 3월 18일
You have two common mistakes here:
- MATLAB class methods require an explicit this input
- obj.prop returns a comma separated list that must be concatenated to use as a vector input.
Fixed Example
classdef agent
properties
r
v
id
end
methods
function y=mean_distance(this,a)
S=sum(norm([a.r]-[this.r]));
y=S/(numel(a)-1);
%I also need a random access iterator to a, like disp(a(i).r(1));
end
end
end
A handle class is not needed for your example often simple small classes that are placed in vectors are better off as value classes.
Usage:
a=agent
a(1).r=5
a(2).r=5
b=a
b(2).r=10
mean_distance(a,b)
% or
a.mean_distance(b)
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Identification에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!