k = linspace(0,0.5)'
h = 6.58212 * 10^-16
m_0 = 9.109383 * 10^-31
E_c = ( h^2 * k.^2 ) / ( 10^-5 * m_0 )
A = [E_c, 1, 2; 3, 4, 5; 6, 7, 8]
运行此代码时,我得到:
error: horizontal dimensions mismatch (100x1 vs 1x1)
error: called from
physics at line 42 column 3
我想计算特征值。但这首先需要具有不会崩溃的矩阵。我意识到E_c是一个100x1向量,我正尝试将其插入3x3矩阵A的第一个插槽中,并且该插槽的大小为1x1。我需要使用elementwise吗?
我们想找到矩阵元素之一是函数的特征值。
答案 0 :(得分:0)
有一些可能性,我添加了tic / toc来衡量执行时间。
k = linspace(0,0.5)';
h = 6.58212 * 10^-16;
m_0 = 9.109383 * 10^-31;
E_c = ( h^2 * k.^2 ) / ( 10^-5 * m_0 );
%% method 1
%% arrayfun, no explicit loop, explicit calculation
tic
ev1 = arrayfun(@(x)eig([x 1 2; 3 4 5; 6 7 8]), E_c', 'unif', false);
ev1 = cell2mat(ev1);
toc
%% method 2
%% arrayfun, no explicit loop, function handle
tic
funEigA = @(x)eig([x 1 2; 3 4 5; 6 7 8]);
ev2 = arrayfun(funEigA, E_c', 'unif', false);
ev2 = cell2mat(ev2);
toc
%% method 3
%% explicit loop, with pre allocation of matrix, explicit calculation, no function handle in loop
tic
ev3 = zeros(length(funEigA(0)),length(E_c)); % evaluate funEigA to determin the number of eigen values. In this case this is 3, because it's a 3x3 matrix.
for ik = 1:length(E_c)
ev3(:,ik) = eig([E_c(ik) 1 2; 3 4 5; 6 7 8]);
end
toc
%% method 4
%% with pre allocation of matrix, explicit loop & call of function handle
tic
ev4 = zeros(length(funEigA(0)),length(E_c));
for ik = 1:length(E_c)
ev4(:,ik) = funEigA(E_c(ik));
end
toc
%% method 5
%% without pre allocation, explicit loop, call of function handle
tic
ev5 = [];
for val = E_c' % k must be a column vector
ev5(:,end+1) = funEigA(val);
end
toc
如果您对每种方法的性能感兴趣,这是我的输出(联想T450,Core i7、3.2 GHz):
Elapsed time is 0.010564 seconds.
Elapsed time is 0.007659 seconds.
Elapsed time is 0.008660 seconds.
Elapsed time is 0.008498 seconds.
Elapsed time is 0.009461 seconds.
我个人喜欢方法#1和#2,因为它很短并且很清楚发生了什么。但是实际上,它们的速度较慢,并且对于使用大容量矩阵的大k或大矩阵,使用性能会比使用优先分配的矩阵低得多。
如果要多次测量执行速度,请确保事先使用clear all
,否则可能会缓存结果。