Reputation: 639
I am trying to add an element to the end of a matrix and i dont know the length of the matrix.
EvantCal = 999*ones(1,2);
.
.
.
.
%// in a different function
EventCal(end + 1) = [1, 3];
%// the numbers are random
.
.
.
this is the error I get when I run the code:
In an assignment A(I) = B, the number of elements in B and I must be the same.
Upvotes: 1
Views: 710
Reputation: 45741
The error is becasue you a trying to stuff a 1-by-2 matrix (i.e. [1, 3]
, which is also the B
from the error message) into a single element of EventCal
(note that the I
in the error message is your end+1
which is a single element). Rather try
EventCal(end+1,:) = [1, 3]
Here the :
refers to all the columns which in your case is 2. Hence 1 row (end+1
is a single number) and 2 columns thus exactly matching the dimensions of your 2-by*1* matrix you are trying to append.
Also, if performance isn't a major issue, you can also use matrix concatenation (but this is less efficient than the indexing approach):
EventCal = [EventCal; [1,3]]
Upvotes: 1