Function with input an array of classes.
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.
Accepted Answer
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)?
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)
Eleftherios Ioannidis
on 18 Mar 2011
Eleftherios Ioannidis
on 19 Mar 2011
0 votes
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!