MATLAB: In an assignment A(:) = B, the number of elements in A and B must be the same.

dimension errorerror

When trying to prove the results of convolution theorem analytically I have run into a deadwall.
The code that I am trying to run is
close all; clear all; clc;
t0=0;
tf=12;
N=5000;
dt=(tf-t0)/N;
t=t0:dt:tf;
for h=1:length(t);
if t(h)<2
x=0;
else if t(h)<4
x(h)=(-0.05/3).*(exp(-3*(t-2))-1);
else
x(h)=(-0.05/3).*((exp(-3.*(t-2))-exp(-3.*(t-4))));
end;
end;
end;
plot(t,x)
axis([t0,tf,0,0.1])
ylabel('x(t)')
xlabel('t')
The error I run into is the following
The ironic thing is if I do it this way
close all; clear all; clc;
t=0:0.0001:2;
x=0;
plot(t,x)
hold on;
t=2:0.0001:4;
x=(-0.05/3)*(exp(-3*(t-2))-1);
plot(t,x);
hold on;
t=4:0.0001:12;
x=(-0.05/3)*(exp(-3*(t-2))-exp(-3*(t-4)));
plot(t,x);
axis([0,12,0,0.05])
ylabel('x(t)')
xlabel('t')
It works and plots the following graph:
Matlab.PNG
Can anyone help me understand where I am going wrong??
P.S: Please keep in mind that my knowledge of MATLAB is mediocre at best so try not to get carried away by using an unknown function.
Thanks in Advance 🙂

Best Answer

Subscript ‘t’ as ‘t(h)’ and it works:
t0=0;
tf=12;
N=5000;
dt=(tf-t0)/N;
t=t0:dt:tf;
for h=1:length(t);
if t(h)<2
x=0;
else if t(h)<4
x(h)=(-0.05/3).*(exp(-3*(t(h)-2))-1);
else
x(h)=(-0.05/3).*((exp(-3.*(t(h)-2))-exp(-3.*(t(h)-4))));
end;
end;
end;
plot(t,x)
axis([t0,tf,0,0.1])
ylabel('x(t)')
xlabel('t')
You can likely avoid the loop and use Vectorization (link).