3

I have writen a class in MATLAB like below:

classdef sizeInfo
properties
end

methods
    function [row column] = getSize(m)
        [row column] = size(m); 
    end
end
end

When I make use of this class's getSize function, it always reports a error like below:

s=sizeInfo
[r c]=s.getSize(data)
Error using sizeInfo/getSize
Too many input arguments.

Anyone knows why?

chappjc
  • 30,359
  • 6
  • 75
  • 132
MengT
  • 1,207
  • 2
  • 14
  • 16

2 Answers2

2

The first parameter of a class function is always a reference to the object itself, thus function [row column] = getSize(m) was a function without parameters and m the implicit passed reference.

classdef sizeInfo
properties
end

methods
    function [row column] = getSize(obj,m)
        [row column] = size(m); 
    end
end
end

One advice: Read the documentation carefully. After learning Java, c++ and python I expected to understand oop. Matlab surprises me again and again.

Daniel
  • 36,610
  • 3
  • 36
  • 69
  • +1, but why the complaint? Passing the reference to self is no different from how Python does it...? – Rody Oldenhuis Oct 22 '13 at 13:17
  • I'm not complaining about this behaviour, but ever tried to implement a singleton pattern which is not broken by `evalin('base','clear all')`, without using java? Sometimes it is nearly impossible to debug why your code does not work in a costumer environment. – Daniel Oct 22 '13 at 13:47
  • 1
    It's more readable to define it as a static method – Mohsen Nosratinia Oct 22 '13 at 14:02
  • 1
    Generally I avoid singletons -- there is almost always a better alternative (see the [wiki](http://en.wikipedia.org/wiki/Singleton_pattern)). And remember: "Try to build a system that even a fool can use, and only fools will use it." :) – Rody Oldenhuis Oct 22 '13 at 14:44
1

For this definition of getSize (which does not need access to an instance of the class) you should define it as Static:

methods(Static)
    function [row column] = getSize(m)
        [row column] = size(m); 
    end
end
Mohsen Nosratinia
  • 9,844
  • 1
  • 27
  • 52