I have a java object (let’s call it Foo) with a length() method.
In MATLAB, I want to write a function that accepts an array of these objects and works with it. My problem is that the usual method of writing a loop breaks down:
function doSomething(someArray)
for i = 1:length(someArray)
% do stuff with someArray(i)
end
because in this case MATLAB decides “oh, that’s a Java object; length(x) should be interpreted as x.length() since it has a length() method:
function printLength(someArray)
disp(length(someArray));
...
> foo = %%% get my handle to the Java Foo object %%%
> printLength([foo foo foo])
3
> printLength([foo foo])
2
> printLength([foo])
300000
% foo.length() gets called and returns 300000 or whatever
Is there a way to get around this?
You can use builtin() to force Matlab to use its own length(), numel(), or whatever functions, ignoring the Java class’s method of the same name. Calling isscalar() or numel() will work most of the time, because Java classes tend not to define methods with those names. But if they do, you’ll get the Java method and have the same problem as with length(). Using builtin() will be more general, working regardless of what methods the Java classes have.
You could wrap it up like this.