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.
For non-empty matrices you can use:
But to cover empty matrices we need more function calls
or more lines
Which both work fine for
m=zeros(0,0)
,m=zeros(0,10)
andm=zeros(10,0)
.A quite general solution is:
It accepts empty matrices (with 0 columns, 0 rows, or both), as well as complex,
NaN
orinf
values.It is also very fast: for a 1000 × 1000 matrix it takes about 22 microseconds in my old laptop (a
for
loop with 1e5 repetitions takes 2.2 seconds, measured withtic
,toc
).How this works:
The keys to handling empty matrices in a unified way are:
[]
);Let r and c be the (possibly zero) numbers of rows and columns of
m
.m(:,[])
is an r × 0 empty vector. This holds even if r or c are zero. In addition, this empty indexing automatically provides insensitivity toNaN
,inf
or complex values inm
(and probably accounts for the small computation time as well).Summing that r × 0 vector along its second dimension (
sum(m(:,[]),2)
) produces a vector of r × 1 zeros. Negating and summing this vector gives r.The same procedure is applied for the number of columns, c, by empty-indexing in the first dimension and summing along that dimension.
Here is a more generic solution
Which
The
find
command has a neat option to get the lastK
elements:To get the size, ask for the last
k=1
elements. For example,You can use
find
with the single output argument syntax, which will give younumel
:Another straightforward, but less interesting solution uses
whos
(thanks for the reminder Navan):Finally, there is
format debug
.Incremental indexing and a try-catch statement works: