MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

### Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

# How do I correct this plot code?

Asked by Joe Johnson on 21 Aug 2012

I am trying to plot an equilibrium equation on Matlab, but I am getting an error of "Error using *, inner matrix dimensions must agree". I have copied the code below.

g = 2.79
k = 1.5
b = 2
a = 3
m = 1
x = -2*pi:.1:2*pi;
y = 3*g*k*((g.^2 - 2*g*a*cos(x) + a.^2).^(1/2) - b)*sin(x)*(1/(m*a))*(1/((g.^2 - 2*g*a*cos(x) + a.^2).^(1/2)));
p = plot(x,y)
set(gca,'XTick',-2*pi:pi/2:2*pi)
set(gca,'XTickLabel',{'-2pi','-3pi/2','-pi','-pi/2','0','pi/2','pi','3pi/2','2pi'})
xlabel('-2\pi \leq \Theta \leq 2\pi')
ylabel('stability')
title('Plot of Stability of Buckling Bar')
text(pi,sin(pi)),'\leftarrow sin(\pi\)',...
'HorizontalAlignment','left')
text(0,sin(0)),'\leftarrow sin(0)',...
'HorizontalAlignment','left')
set(p,'Color','red','LineWidth',2)


## Products

No products are associated with this question.

Answer by Azzi Abdelmalek on 21 Aug 2012
Edited by Azzi Abdelmalek on 21 Aug 2012

you have forgoten some .* or ./

   g = 2.79 ;k = 1.5; b = 2; a = 3 ;m = 1 ;x = -2*pi:.1:2*pi;
y = 3*g*k*((g.^2 - 2*g*a*cos(x) + a.^2).^(1/2) - b).*sin(x)*(1/(m*a)).*(1./((g.^2 - 2*g*a*cos(x) + a.^2).^(1/2)));
p = plot(x,y)
set(gca,'XTick',-2*pi:pi/2:2*pi)
set(gca,'XTickLabel',{'-2pi','-3pi/2','-pi','-pi/2','0','pi/2','pi','3pi/2','2pi'})
xlabel('-2\pi \leq \Theta \leq 2\pi')
ylabel('stability') ,
title('Plot of Stability of Buckling Bar')
text(pi,sin(pi),'\leftarrow sin(\pi)','HorizontalAlignment','left')
text(0,sin(0),'\leftarrow sin(\0)','HorizontalAlignment','left')
set(p,'Color','red','LineWidth',2)

Answer by Matt Fig on 21 Aug 2012
Edited by Matt Fig on 21 Aug 2012

Whenever you mean to multiply (or divide) a vector by a vector on an element-by-element basis, you must use the (.*) or (./) operator instead of (*) or (/). Remember MATLAB was originally a matrix language, so it interprets the latter operators as matrix multiply.

Try this to fully see what I mean:

A = [1 2 3];
B = [4 5 6];

A.*B    % = [A(1)*B(1),A(2)*B(2),A(3)*B(3)]
A*B     % error because a a 1-by-3 cannot multiply a 1-by-3
A*(B')  % = A(1)*B(1) + A(2)*B(2) + A(3)*B(3) matrix multiplication.


To avoid this it is always best to just use all .* when doing non-matrix multiplication and division.