Function with input an array of classes.
9 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Andrew Newell
on 18 Mar 2011
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 Comments
More Answers (4)
Andrew Newell
on 18 Mar 2011
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 Comments
Philip Borghesani
on 18 Mar 2011
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 Comments
See Also
Categories
Find more on Data Type Identification in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!