matlab - 八度误差:水平尺寸不匹配 - 矩阵元素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。我需要使用元素来做到这一点吗?
我们想要找到其中一个矩阵元素是函数的特征值。
解决方案
这里有一些可能性,我添加了 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.
就个人而言,我喜欢方法#1 和#2,因为它简短而清晰。但实际上它们速度较慢,并且对于使用单元阵列的大 k 或大矩阵可能会变得比使用预分配矩阵的性能要低得多。
如果您想多次测量执行速度,请确保您clear all
事先使用,否则可能会缓存结果。
推荐阅读
- c# - C# - 按元素的首字母排序列表 (StartsWith)
- c# - 将两个随机生成的数字相乘,直到满足条件
- jenkins - Jenkinsfile 库方法文档
- three.js - 提取动画顶点
- jquery - 未捕获的类型错误:$(...).indexOf 不是函数
- vb.net - 初学者 - 在 Datagridview (VB.net) 中选择一行
- android - 如何立即获得 JSON 响应
- javascript - 未捕获的 SyntaxError:请求的模块“./add.js”未提供名为“add”的导出
- python - 为networkx中的特定节点着色
- r - 按月和年排序 R