我正在尝试使用 MatLab 代码作为程序员学习数学的一种方式。
所以阅读我这篇关于子空间的文章并尝试构建一些简单的 matlab 函数来为我做这件事。
这是我走了多远:
function performSubspaceTest(subset, numArgs)
% Just a quick and dirty function to perform subspace test on a vector(subset)
%
% INPUT
% subset is the anonymous function that defines the vector
% numArgs is the the number of argument that subset takes
% Author: Lasse Nørfeldt (Norfeldt)
% Date: 2012-05-30
% License: http://creativecommons.org/licenses/by-sa/3.0/
if numArgs == 1
subspaceTest = @(subset) single(rref(subset(rand)+subset(rand))) ...
== single(rref(rand*subset(rand)));
elseif numArgs == 2
subspaceTest = @(subset) single(rref(subset(rand,rand)+subset(rand,rand))) ...
== single(rref(rand*subset(rand,rand)));
end
% rand just gives a random number. Converting to single avoids round off
% errors.
% Know that the code can crash if numArgs isn't given or bigger than 2.
outcome = subspaceTest(subset);
if outcome == true
display(['subset IS a subspace of R^' num2str(size(outcome,2))])
else
display(['subset is NOT a subspace of R^' num2str(size(outcome,2))])
end
这些是我正在测试的子集
%% Checking for subspaces
V = @(x) [x, 3*x]
performSubspaceTest(V, 1)
A = @(x) [x, 3*x+1]
performSubspaceTest(A, 1)
B = @(x) [x, x^2, x^3]
performSubspaceTest(B, 1)
C = @(x1, x3) [x1, 0, x3, -5*x1]
performSubspaceTest(C, 2)
运行代码给了我这个
V =
@(x)[x,3*x]
subset IS a subspace of R^2
A =
@(x)[x,3*x+1]
subset is NOT a subspace of R^2
B =
@(x)[x,x^2,x^3]
subset is NOT a subspace of R^3
C =
@(x1,x3)[x1,0,x3,-5*x1]
subset is NOT a subspace of R^4
C 不起作用(仅当它只接受一个 arg 时才起作用)。我知道我对 numArgs 的解决方案不是最优的——但这是我目前能想到的。
有什么方法可以优化这段代码,使 C 能够正常工作,并且可能避免超过 2 个参数的elseif语句..?
PS:我似乎找不到一个内置的 matlab 函数来为我做这个洞的事情..