首页 > 解决方案 > 八度误差:水平尺寸不匹配 - 矩阵元素matlab

问题描述

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。我需要使用元素来做到这一点吗?

我们想要找到其中一个矩阵元素是函数的特征值。

标签: matlabmatrixoctaveelementwise-operations

解决方案


这里有一些可能性,我添加了 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

如果您对每种方法的性能感兴趣,这是我的输出(Lenovo 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.

或者,运行 1000 次后: 在此处输入图像描述

就个人而言,我喜欢方法#1 和#2,因为它简短而清晰。但实际上它们速度较慢,并且对于使用单元阵列的大 k 或大矩阵可能会变得比使用预分配矩阵的性能要低得多。

如果您想多次测量执行速度,请确保您clear all事先使用,否则可能会缓存结果。


推荐阅读