简体   繁体   English

如何在Matlab中使尺寸一致?

[英]How to make the dimensions agree in Matlab?

I am just starting to learn Matlab, and I would be very grateful if someone could clarify my confusion... 我刚刚开始学习Matlab,如果有人能澄清我的困惑,我将不胜感激。

I am trying to solve a non-uniform transport equation using the Lax-Wendroff scheme, with the code below. 我正在尝试使用Lax-Wendroff方案(以下代码)来解决一个非均匀输运方程。 Matlab tells me that there are errors in the last line of the code (U(j+1,2:N)=(1/2).*sigma...), that is, 1. Error using *; Matlab告诉我,代码的最后一行存在错误(U(j + 1,2:N)=(1/2)。* sigma ...),即1.使用*时出错; 2. Inner matrix dimensions must agree. 2.内部矩阵尺寸必须一致。

I know the dimensions of sigma and U's are not compatible (as matrices), but I have no idea (and experience) on how to fix this... There's no problem with the formula, but I really find it hard to deal with the code. 我知道sigma和U的维数不兼容(作为矩阵),但是我不知道(也没有经验)如何解决此问题……该公式没有问题,但是我真的很难解决码。

    a = -10;
    b = 10;
    delta_x = (b-a)/N;
    x = a:delta_x:b;

    tfinal = 2;
    delta_t = tfinal/M;
    t = 0:delta_t:tfinal;

    c = 3-2.* exp(-(1/4).*(x.^2)) ;

    sigma = c.*(delta_t/delta_x);

    U=zeros(M+1,N+1);
    U(1,:)=f(x);

    for j=1:M
    U(j+1,2:N)=(1/2).*sigma.*(sigma-1).*U(j,3:N+1)-((sigma).^2-1).*U(j,2:N)+(1/2).*sigma.*(sigma+1)*U(j,1:N-1);
    end

Thank you so much! 非常感谢!

I have added the size of each variable as a comment and formatted the code a bit. 我添加了每个变量的大小作为注释,并对代码进行了格式化。 It is still the same code as you posted. 它仍然是您发布的相同代码。

a = -10;
b = 10;
delta_x = (b-a)/N;
x = a:delta_x:b;                   % x: 1 x ( N + 1 )

tfinal = 2;
delta_t = tfinal/M;
t = 0:delta_t:tfinal;              % t: 1 x ( M + 1 )

c = 3-2.* exp(-(1/4).*(x.^2)) ;    % c: 1 x ( N + 1 )

sigma = c.*(delta_t/delta_x);      % sigma: 1 x ( N + 1 )

U=zeros(M+1,N+1);                  % U: ( M + 1 ) x ( N + 1 )
U(1,:)=f(x);                       % Assuming f(x): 1 x ( N + 1 ), otherwise you will get an error here.

for j=1:M
    U(j+1,2:N) = (1/2).*sigma.*(sigma-1).*U(j,3:N+1) ...
                -((sigma.^2)-1).*U(j,2:N) ...
                +(1/2).*sigma.*(sigma+1)*U(j,1:N-1);
end

You will notice that in first line of for -loop you are multiplying sigma (of size 1 x ( N + 1 ) ) with U(j, 3:N+1) (size: 1 x (N - 1) ). 您会注意到,在for -loop的第一行中for您将sigma (大小为1 x ( N + 1 ) )乘以U(j, 3:N+1) (大小: 1 x (N - 1) )。 This will not work. 这是行不通的。 You do the same thing for next two lines of for -loop, where the size of U(j,...) is not same as size of sigma . 对于for循环的后两行,您执行相同的操作,其中U(j,...)大小与sigma大小不同。

I do not know what the actual equation looks like, so can not say for sure how you need to correct for the size mismatch. 我不知道实际的方程式是什么样子,所以不能肯定地说您需要如何校正尺寸不匹配。 But you can try replacing sigma by say sigma(3:N+1) or something equivalent to get the right size. 但是您可以尝试通过说sigma(3:N+1)或等同的方法替换sigma ,以获得正确的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM