为什么会出现vertcat错误? (Matlab)

时间:2018-11-16 04:58:53

标签: matlab matrix

我试图针对时间t绘制矩阵的第一行,但无法弄清楚为什么矩阵会产生错误:“ vertcat: 串联的矩阵的尺寸不一致。” enter image description here

t = linspace(0,100);

y_mat = (1./t).*([1, t+(1/2)*exp(-3*t)-(1/2)*exp(-t); 
(3/2)*(exp(-t)-exp(-3*t)), 1-(3/2)*exp(-3*t)+ 
(1/2)*exp(-t)] * [(t-4)/3;1]);

plot(t,y_mat(1,:))

3 个答案:

答案 0 :(得分:3)

您在用符号表示法进行思考,但以矩阵表示法实现。当您执行t = linspace(0,100);时,它将创建一个1x100矩阵(数组)。因此,稍后在y_mat的定义中使用它时,定义中使用的每个表达式都将求值为1x100矩阵。因此,您的y_mat定义就是这样做的:[1x100] * [1 1x100 ; 1x100 1x100] * [1x100 ; 1]显然会失败。

您有两个选择: 首先通过分别计算矩阵乘法并重新构造矩阵以表示实际乘法(确保1被正确复制),以矩阵符号进行所有计算。

OR

使用Matlabs的symbolic variables and expressions大概是这样的:

syms t  % creating symbolic variable
% creating symbolic expressions
f0 = 1/t  
f1 = t+(1/2)*exp(-3*t)-(1/2)*exp(-t);
f2 = (3/2)*(exp(-t)-exp(-3*t));
f3 = 1-(3/2)*exp(-3*t)+(1/2)*exp(-t);
f4 = (t-4)/3;
% defining y_mat
y_mat = f0 * [1 f1; f2 f3] * [f4 ; 1]

% putting value in symbolic variable
t = linspace(eps,100); % eps to avoid division by 0 error

% substitute values and evaluate y_mat
y_mat_vals = eval(subs(y_mat));

这为y_mat_vals提供了一个2x100矩阵作为答案。

答案 1 :(得分:1)

您弄糟了您的代码。.键入此类函数时需要小心。为简单起见,我使用了一个循环。

t = linspace(0,100);

nt = length(t) ;
y_mat = zeros(2,nt) ;

for i = 1:nt
y_mat(:,i) = (1/t(i))*([1           t(i)+(1/2)*exp(-3*t(i))-(1/2)*exp(-t(i));
    (3/2)*(exp(-t(i))-exp(-3*t(i)))   1-(3/2)*exp(-3*t(i))+(1/2)*exp(-t(i))])*[(t(i)-4)/3;1];
end
plot(t,y_mat)

enter image description here

答案 2 :(得分:1)

您也可以更明确地将其写出。等式如下:

AmericanTexts3 <- gsub("Embed.*})});\n", "", AmericanTexts)

由于这些项都是标量,因此可以使用逐元素乘法同时为所有[ 1,pt2 ; pt3,pt4 ] * [ pt5 ; 1 ] = [ pt5 + pt2 ; pt3.*pt5 + pt4 ] 计算它们:

t

这可能有点冗长,但我认为它的可读性并不比其他解决方案差。而且效率更高:对于具有500个元素的t = linspace(0,100); pt2 = t+(1/2)*exp(-3*t)-(1/2)*exp(-t); pt3 = (3/2)*(exp(-t)-exp(-3*t)); pt4 = 1-(3/2)*exp(-3*t)+(1/2)*exp(-t); pt5 = (t-4)/3; y_mat = (1./t) .* [ pt5 + pt2 ; pt3.*pt5 + pt4 ]; plot(t,y_mat) ,效率是0.0571 ms,而483.3 ms(syms solution)和0.681 ms(loop solution))。

(请注意,乘以t会使用隐式单例扩展。这在MATLAB R2016b和更高版本中适用。对于旧版本的MATLAB,请使用1./t。)