Matlab: finding the length of an array of java objects

I have a java object (let it be called Foo) using a method length().

In MATLAB, I want to write a function that takes an array of these objects and works with it. My problem is that the usual method of writing a loop breaks up:

function doSomething(someArray)
    for i = 1:length(someArray)
        % do stuff with someArray(i)
    end

because in this case MATLAB decides "oh, what the Java object is; length(x)it should be interpreted as x.length(), because 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 any way around this?

+3
source share
4 answers

builtin(), Matlab length(), numel() , Java . isscalar() numel() , Java . , Java , length(). builtin() , , Java.

>> foo = java.lang.String('foo');
>> builtin('length', [foo foo])
ans =
     2
>> builtin('length', [foo])
ans =
     1
>> length([foo])
ans =
     3
>> 

.

function out = mlength(x)
%MLENGTH Array length, ignoring Java length() methods

% Test for isjava to avoid ignoring overriden length() methods in Matlab objects
if isjava(x)
   out = builtin('length', x);
else
   out = length(x);
end
+3

- :

>> jPanel = javax.swing.JPanel;
>> length({jPanel,jPanel,jPanel})
ans = 
    3
>> length({jPanel,jPanel})
ans = 
    2
>> length({jPanel})
ans = 
    1
>> length({})
ans = 
    0

someArray{i} someArray(i)

+3

NUMEL LENGTH? (.. ), length.

+1
source

Hmm, this seems to work ....

function printLength(someArray)
if (isscalar(someArray))
    L = 1;
else
    L = length(someArray);
end
disp(L);
0
source

Source: https://habr.com/ru/post/1751755/


All Articles