简体   繁体   中英

Subscripted assignment dimension mismatch error in Matlab

I get the next error executing this command in Matlab:

% dibuji sixmin
x_lim=-2:.1:2; y_lim=-1:0.1:1;
[x(1), x(2)]= meshgrid(x_lim, y_lim);

z = (-exp^(-(x(1) + x(2))))*((sin(3*x(1)))^2)*((sin(3*x(2)))^2);

subplot(2,1, 1)
surf(x(1), x(2), z, 'edgecolor', 'none', 'facecolor', 'interp');
grid on
title('mi_sixmin')

subplot(2,1, 2)
contour(x(1),x(2),z,20)
grid on

Anyone could help me to solve it?

There seems to be 3 problems with your code.

First, the command [X, Y] = meshgrid(x_lim, y_lim) creates two 21x41 matrices and saves them to X and Y . So, the second line of your code ( [x(1), x(2)]= meshgrid(x_lim, y_lim); ) is attempting to insert a 21x41 matrix into the first element of x , and a 21x41 matrix into the second element of x . The reason that this does not work is that the each element of the matrix x can only fit 1 element. In other words, x(1) can only fit a 1x1 matrix. To fix this, replace x(1) with X and x(2) with Y . This way, the two 21x41 matrices are saved to their own variables.

Second, note that exp() is a function, and not a variable. So, the fourth line of your function should have exp(-(X+Y)) instead of exp^(-(X+Y)) .

Third, I believe you are trying to do element-wise operations in that same line. Instead, the code specifies matrix multiplication. To specify element-wise operarations, use .* and .^ . So, the fourth line of your code should be: z = (-exp(-(X + Y))).*((sin(3*X)).^2).*((sin(3*Y)).^2);

So, your edited code should look like this now:

x_lim=-2:.1:2; y_lim=-1:0.1:1;
[X, Y]= meshgrid(x_lim, y_lim);

z = (-exp(-(X + Y))).*((sin(3*X)).^2).*((sin(3*Y)).^2);

subplot(2,1, 1)
surf(X, Y, z, 'edgecolor', 'none', 'facecolor', 'interp');
grid on
title('mi_sixmin')

subplot(2,1, 2)
contour(X,Y,z,20)
grid on

There are some errors in your script:

  • evalaution of meshgrid : the output are 2 matrices while you specifying x(1) and x(2) define 2 scalars
  • evaluation of z : exp does not require ^ it is "already" the exponential; also, since you are working with matrices (generated by meshgrid ) all the operand have to be preceded by . (a dot) in order they are applied to each element of the matrices

This is the updated code.

x_lim=-2:.1:2; y_lim=-1:0.1:1;
[X, Y]= meshgrid(x_lim, y_lim);

z = (-exp(-(X + Y))).*((sin(3*X)).^2).*((sin(3*Y)).^2);

subplot(2,1, 1)
surf(X, Y, z, 'edgecolor', 'none', 'facecolor', 'interp');
grid on
title('mi_sixmin')

subplot(2,1, 2)
contour(X,Y,z,20)
grid on

在此处输入图片说明

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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