MATLAB: “Unable to perform assignment because the indices on the left side are not compatible with the size of the right side.” Error when assigning values of a sum to an empty vector.

errorMATLAB

I'm trying to compute the following sum:
c = [];
for n = 1:k
c(n) = (4*(-1)^n / (2*n + 1)*pi) .* cos(((2*n + 1)*pi*x) / 2) .* exp(-(((2*n + 1)*pi) / 2)^2 * t );
end
Where k is a scalar, x is a 1×100 vector, and t is a 1×100 vector. I get the following error:
"Unable to perform assignment because the indices on the left side are not compatible with the size of the right side."
How do I fix this?
Thanks!

Best Answer

You are trying assign 100 values to a single entry in c. You need to either
  1. specify rows and columns in c that are the same size as your result or
  2. make c a cell array by using curly braces instead of parentheses.
If you are instead expecting a single value as your result, check your equation.
As a simple example
% this works

a(1,:) = [1 2]
a = 1×2
1 2
% this works
b{1} = [1 2]
b = 1x1 cell array
{1×2 double}
% this does not
c(1) = [1 2]
Unable to perform assignment because the indices on the left side are not compatible with the size of the right side.