查找矩阵的大小,而无需在MATLAB中使用"size" [英] Find size of matrix, without using `size` in MATLAB
问题描述
假设我想查找矩阵的大小,但是不能使用任何功能,例如size
,numel
和length
.有没有整齐的方法可以做到这一点?我可以想到一些使用循环的版本,例如以下版本,但是有可能在没有循环的情况下做到这一点?
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.
推荐答案
这是更通用的解决方案
function sz = find_size(m)
sz = [];
m(f(end), f(end));
function r = f(e)
r=[];
sz=[sz e];
end
end
哪个
- 适用于数组,单元格数组和对象数组
- 它的时间复杂度是恒定的,并且与矩阵大小无关
- 不使用任何MATLAB函数
- 易于适应更高的尺寸
- Works for arrays, cell arrays and arrays of objects
- Its time complexity is constant and independent of matrix size
- Does not use any MATLAB functions
- Is easy to adapt to higher dimensions
这篇关于查找矩阵的大小,而无需在MATLAB中使用"size"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!