1

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.

Dan
  • 45,079
  • 17
  • 88
  • 157
Elad L.
  • 629
  • 1
  • 10
  • 25

1 Answers1

1

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]]
Community
  • 1
  • 1
Dan
  • 45,079
  • 17
  • 88
  • 157
  • thanks, this works but not in the way im trying, i need it to go to the next line so it will look like a matrix and not an array – Elad L. Dec 21 '15 at 10:46
  • Sorry, just reread the question and saw your initialization. See the edit – Dan Dec 21 '15 at 10:46
  • @user2336124 no problem, please mark this as correct if it solved your issue. – Dan Dec 21 '15 at 12:22