Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find size of matrix, without using `size` in MATLAB

Suppose I want to find the size of a matrix, but can't use any functions such as size, numel, and length. Are there any neat ways to do this? I can think of a few versions using loops, such as the one below, but is it possible to do this without loops?

function sz = find_size(m)
sz = [0, 0]
   for ii = m'    %' or m(1,:) (probably faster)
      sz(1) = sz(1) + 1;
   end

   for ii = m     %' or m(:,1)'
      sz(2) = sz(2) + 1;
   end    
end

And for the record: This is not a homework, it's out of curiosity. Although the solutions to this question would never be useful in this context, it is possible that they provide new knowledge in terms of how certain functions/techniques can be used.

like image 885
Stewie Griffin Avatar asked Oct 09 '13 18:10

Stewie Griffin


1 Answers

Here is a more generic solution

function sz = find_size(m)
sz = [];
m(f(end), f(end));
    function r = f(e)
        r=[];
        sz=[sz e];
    end
end

Which

  1. Works for arrays, cell arrays and arrays of objects
  2. Its time complexity is constant and independent of matrix size
  3. Does not use any MATLAB functions
  4. Is easy to adapt to higher dimensions
like image 113
Mohsen Nosratinia Avatar answered Sep 28 '22 16:09

Mohsen Nosratinia